Depedency injection in custom X509CertificateValidator class in WCF using Unity

We are using WCF service along with certificate based authentication with wsHttpBinding.

I have written custom class to do authentication. This class is inhereting from System.IdentityModel.Selectors.X509CertificateValidator.

 public class MyX509CertificateValidator : System.IdentityModel.Selectors.X509CertificateValidator
    {


        public override void Validate(X509Certificate2 certificate)
        {
            /// Custom code goes here
        }
    }

This class is configured in web.config

 <behavior name="customBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceCredentials>
            <clientCertificate>
              <authentication certificateValidationMode="Custom"
                              customCertificateValidatorType="**SampleClass.MyX509CertificateValidator** ,SampleClass"
                              revocationMode="NoCheck"/>
            </clientCertificate>
            <serviceCertificate
              findValue="XXXXXXXXXXXXXXXX"
              x509FindType="FindByThumbprint"
              storeLocation="CurrentUser"
              storeName="My"/>
          </serviceCredentials>

I am using Unity.WCF nuget package for adding DI support to the WCF. My problem is I am unable inject dependency inside above class. This class is not served by Unity. It is being called automatcally by WCF runtime when WCF is invoked.

Can we really add dependency injection support in above class?

Answers


You can still inject dependencies into a custom certificate validator:

You can accept it via the constuctor:

public class CertificateValidator : X509CertificateValidator
{
    private IMyDependency _dependency;

    public CertificateValidator(IMyDependency dependency)
    {
        _dependency = dependency;
    }

    public override void Validate(X509Certificate2 certificate)
    {
        ...

And then pass it when you configure the service host:

serviceHost.Credentials.ClientCertificate.Authentication.CustomCertificateValidator =
    new CertificateValidator(dependency);

You can use an IOC container to supply the dependency to the part of your program that creates the service host.


Need Your Help

LINQ2SQL - Binding result to a grid - want changes to be reflected without re-binding?

c# linq-to-sql data-binding winforms

I have a grid (DevExpress XtraGrid, if that matters) which is bound to a LINQ to SQL Entity property.

Mysql does not escape & special char

php mysql

I m tring to escape the &amp; [ampersand] char in mysql query in php, I tired using: