我正在使用fluentvalidation并使用structuremap为asp.net mvc3中的操作注入验证器。我在将业务对象注入验证器对象时遇到问题。我得到这样一个错误:
{"StructureMap异常代码:202\n没有为PluginFamily Suggestion.Biz.BO.ISubjectBO,Suggestion.Biz,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null定义默认实例"}
如何将SubjectBO注入SubjectValidator?
主题验证器:
public class SubjectValidator : AbstractValidator<SUBJECT>
{
private ISubjectBO _subjectBO;
public SubjectValidator(ISubjectBO subjectBO)
{
_subjectBO = subjectBO;
Custom(x=>{
if(!_subjectBO.CanUpdate(x))
return new ValidationFailure(null, "error msg");
return null;
});
}
}
建议验证注册表:
public class SuggestionValidationRegistry : Registry
{
public SuggestionValidationRegistry()
{
For<IValidator<SUBJECT>>().Singleton().Use<SubjectValidator>();
ValidatorOptions.ResourceProviderType = typeof(ValidationResources);
}
}
StructureMap ValidatorFactory:
public class StructureMapValidatorFactory : ValidatorFactoryBase
{
public override IValidator CreateInstance(Type validatorType)
{
return ObjectFactory.TryGetInstance(validatorType) as IValidator;
}
}
应用程序启动:
ObjectFactory.Configure(cfg => cfg.AddRegistry(new SuggestionValidationRegistry()));
FluentValidationModelValidatorProvider.Configure(provider => provider.ValidatorFactory = new StructureMapValidatorFactory());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
是,我在app_start配置建议BizRegistry:
public class BizRegistry : Registry
{
public BizRegistry()
{
For<IAwardTypeBO>().Use<AwardTypeBO>();
For<IQuoteBO>().Use<QuoteBO>();
For<ISubjectBO>().Use<SubjectBO>();
For<IContestBO>().Use<ContestBO>();
For<IApplicationBO>().Use<ApplicationBO>();
For<IScreenBO>().Use<ScreenBO>();
}
}
应用程序启动:
protected void Application_Start()
{
ConfigureStructureMap();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
EFUnitOfWorkFactory.SetObjectContext(() => new SuggestionModel());
UnitOfWork.UnitOfWorkFactory = new EFUnitOfWorkFactory();
}
private static void ConfigureStructureMap()
{
IContainer container = new Container(x =>
{
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
x.AddRegistry(new BizRegistry());
});
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
ObjectFactory.Configure(cfg => cfg.AddRegistry(new SuggestionValidationRegistry()));
FluentValidationModelValidatorProvider.Configure(provider => provider.ValidatorFactory = new StructureMapValidatorFactory(container));
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
}
在配置SubjectValidator
注入时,您尚未配置构造函数参数ISubjectBO subjectBO
您可以按照本线程中的说明编写一个自定义验证器工厂。