我是结构图的新手。当我将属性注入用于自定义验证类时,该属性始终为空。我想我错过了一些东西。在这方面的任何帮助将不胜感激。我不想使用 System.Web.Mvc.DependencyResolver.Current.GetService(); 在 AddressInfoValidator 中获取记录器的实例。我们使用 MVC 5、FluentValidation.Mvc(5.1.0.0) 和 Structure map(2.6.3.0) 来注入依赖项。我有一个简单的日志外观和一个 Myloger 类:
public class LogingFacade : ILogingFacade
{
private IMyLoger loger;
LogingFacade(IMyLoger myLoger)
{
this.loger = myLoger;
}
public void SaveToLog()
{
this.loger.SendError();
}
}
public class MyLoger : IMyLoger
{
public void SendError()
{
//send to DB
}
}
验证器的实现如下,我使用了属性注入,因为下面的类将用作属性:
public class AddressInfoValidator : AbstractValidator<AddressInfo>, IValidatorInterceptor
{
public AddressInfoValidator()
{
this.RuleFor(x => x.StreetAddress).NotEmpty().Length(1, 50);
this.RuleFor(x => x.UnitNumber).Length(0, 20);
this.RuleFor(x => x.City).NotEmpty().WithMessage(UIErrorMessages.MSG_UI_00001).Length(1, 50).WithMessage(UIErrorMessages.MSG_UI_00002);
this.RuleFor(x => x.State).NotEmpty();
this.RuleFor(x => x.ZipCode).NotEmpty().Length(1, 20).Matches("\\d{5}");
}
[SetterProperty]
public ILogingFacade Logger { get; set;}
public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result)
{
try
{
result.Errors.ToList().ForEach(r =>
{
this.Logger.SaveToLog(new ValidationError { PropertyName = r.PropertyName, AttemptedValue = r.AttemptedValue, ErrorMessage = r.ErrorMessage });
});
}
catch (System.AggregateException)
{
// TODO log the exception
}
return result;
}
public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext)
{
return validationContext;
}
}
地址模型是:
[Validator(typeof(AddressInfoValidator))]
public class AddressInfo
{
public string StreetAddress{ get; set;}
public string UnitNumber{ get; set;}
public string ZipCode{ get; set;}
public string City
public string State{ get; set;}
}
在 global.asax 中启动时从应用程序调用的结构映射注册表:
[CLSCompliant(false)]
public class ServiceUiWebRegistry : Registry
{
public ServiceUiWebRegistry()
{
this.For<IMyLoger>().Use<IMyLoger>();
this.For<ILogingFacade>().Use<LogingFacade>();
this.FillAllPropertiesOfType<ILogingFacade>();
}
}