我正在使用NinjectHttpApplication
我的项目中定义的几个模块。
我想要的是创建FluentValidation
验证工厂,如http://www.thekip.nl/2011/09/22/using-fluentvalidation-for-both-domain-validation-and-validation-in-mvc-projects/中所述。
要创建一个具体的验证工厂,我需要覆盖
IValidator CreateInstance(Type validatorType)
然后我应该调用的方法
return kernel.Get<validatorType>() as IValidator
但我读过Global.asax
不建议在范围之外使用 IKernel。
有什么选择可以做我想要的?
编辑:使用 Ninject-FluentValidation 扩展
正如雷莫所说,有一个扩展GitHub
(https://github.com/ninject/ninject.web.mvc.fluentvalidation)。扩展中有一个类:
public class NinjectValidatorFactory : ValidatorFactoryBase { ... }
它接受IKernel
构造函数并创建实例IValidator
public override IValidator CreateInstance(Type validatorType)
{
if(((IList<IBinding>)Kernel.GetBindings(validatorType)).Count == 0)
{
return null;
}
return Kernel.Get(validatorType) as IValidator;
}
然后我的代码如下:
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;
}
}
这样可行。我不知道它是否可以更好地解决。另外我不明白需要IKernel
在NinjectValidationFactory
.