FluentValidation验证工厂和Ninject DI容器

lex*_*eme 4 c# dependency-injection ninject fluentvalidation

我正在使用NinjectHttpApplication我的项目中定义的几个模块.

我想要的是创建FluentValidation验证工厂,如http://www.thekip.nl/2011/09/22/using-fluentvalidation-for-both-domain-validation-and-validation-in-mvc-projects/中所述.

要创建一个具体的验证工厂,我需要覆盖

IValidator CreateInstance(Type validatorType) 
Run Code Online (Sandbox Code Playgroud)

然后我应该打电话的方法

return kernel.Get<validatorType>() as IValidator
Run Code Online (Sandbox Code Playgroud)

但我已经读过,Global.asax建议不要在范围之外使用IKernel .

有什么选择可以制作我想要的东西?

编辑:使用Ninject-FluentValidation扩展

正如雷莫所说,GitHub(https://github.com/ninject/ninject.web.mvc.fluentvalidation)有一个扩展名.扩展中有一个类:

public class NinjectValidatorFactory : ValidatorFactoryBase { ... }
Run Code Online (Sandbox Code Playgroud)

它接受IKernel构造函数并创建实例IValidator

public override IValidator CreateInstance(Type validatorType)
{
    if(((IList<IBinding>)Kernel.GetBindings(validatorType)).Count == 0)
    {
        return null;
    }

    return Kernel.Get(validatorType) as IValidator;
}
Run Code Online (Sandbox Code Playgroud)

然后我的代码就像:

public class MvcApplication : NinjectHttpApplication
{
    private NinjectValidatorFactory nvfactory;

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());                        
    }
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
        );
    }        
    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(nvfactory));            
    }
    protected override IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());            
        nvfactory = new NinjectValidatorFactory(kernel);

        return kernel;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样可行.我不知道它能否更好地解决.另外,我不明白需要公开IKernel作为公共财产NinjectValidationFactory.

Rem*_*oor 10

Ninject.Web.Mvc.FluentValidation扩展为Ninject添加了对流畅验证的支持.它可以在NuGet上找到.请参阅https://github.com/ninject/ninject.web.mvc.fluentvalidation