我正在使用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?
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;
});
}
}
SuggestionValidationRegistry:
public class SuggestionValidationRegistry : Registry
{
public SuggestionValidationRegistry()
{
For<IValidator<SUBJECT>>().Singleton().Use<SubjectValidator>();
ValidatorOptions.ResourceProviderType = typeof(ValidationResources);
}
}
StructureMapValidatorFactory:
public class StructureMapValidatorFactory : ValidatorFactoryBase
{
public override IValidator CreateInstance(Type validatorType)
{
return ObjectFactory.TryGetInstance(validatorType) as IValidator;
}
}
App_start:
ObjectFactory.Configure(cfg => cfg.AddRegistry(new SuggestionValidationRegistry()));
FluentValidationModelValidatorProvider.Configure(provider => provider.ValidatorFactory = new StructureMapValidatorFactory());
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
是的,我在app_start配置 SuggestionBizRegistry:
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>();
}
}
App_start:
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;
}
答案 0 :(得分:0)
您可以按照this thread中的说明编写自定义验证工厂。
答案 1 :(得分:0)
配置ISubjectBO subjectBO
注入
SubjectValidator