Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject an object into a WCF validator class

Following up on using dependency injection for WCF services, is there any way of using DI for WCF validators, so that one could do this:

public class DIValidator : UserNamePasswordValidator
{
    private readonly IService service;

    [Inject]
    public DIValidator(IService service)
    {
        this.service = service;
    }

    public override void Validate(string userName, string password)
    {
        service.Login(userName, password);
    }
}

EDIT - I tried to apply Dzmitry's advice to my custom behaviour extension, since my validator is defined in app.config. Sadly I get a MethodMissingException, since wcf wants my validator to have a default constructor:

System.MissingMethodException: No default constructor has been defined for this object.

at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)

Here is my behavior class:

    public class DependencyInjectionServiceBehavior : BehaviorExtensionElement, IServiceBehavior
    {
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            serviceHostBase.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = DISupport.Kernel.Get<IService>();
        }
    }
like image 770
Blake Pettersson Avatar asked Jul 24 '09 07:07

Blake Pettersson


1 Answers

In general custom validator is assigned programmatically (there is also possibility to do so from config file) something like this and it is done just before service host is opened and basically this is also the time you create your DI container instance that will be further used to service instances through instance provider:

serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new LocalUserNamePasswordValidator();

You can as well use DI container to create your custom validator as well.

serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = unityContainer.Resolve<UserNamePasswordValidator>();
like image 116
Dzmitry Huba Avatar answered Oct 04 '22 02:10

Dzmitry Huba