如何将对象注入WCF验证器类

Bla*_*son 11 .net wcf dependency-injection ninject wcf-security

继续对WCF服务使用依赖注入,是否有任何方法可以将DI用于WCF 验证器,以便可以执行此操作:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 我试图将Dzmitry的建议应用于我的自定义行为扩展,因为我的验证器是在app.config中定义的.遗憾的是我得到一个MethodMissingException,因为wcf希望我的验证器有一个默认的构造函数:

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)

这是我的行为类:

    public class DependencyInjectionServiceBehavior : BehaviorExtensionElement, IServiceBehavior
    {
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            serviceHostBase.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = DISupport.Kernel.Get<IService>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

mac*_*kow 2

我知道这不是您正在寻找的解决方案,但我会创建一个默认构造函数,该构造函数将从您的 IoC 容器(服务定位器而不是 DI)获取 IService。这不是最好的方法,但却是我能想到的最简单的方法。

编辑:当然,如果您需要模拟 IService 进行测试或任何其他目的,您可以保留允许您注入依赖项的构造函数。