使用MVC ValidationAttribute的Autofac属性注入
本文关键字:属性 注入 Autofac MVC ValidationAttribute 使用 | 更新日期: 2023-09-27 18:24:07
我发现了关于这个主题的几个问题,但还没有找到一个干净简单的解决方案。
这就是我正在做的(使用Autofac 3.3.0)注册
builder.RegisterType<MerchantRepo>().As<IMerchantRepo>().PropertiesAutowired();
这是我的验证类
public class MerchantMustBeUniqueAttribute : ValidationAttribute
{
public IMerchantRepo MerchantRepo { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int merchantId = Convert.ToInt32(value);
if (MerchantRepo.Exists(merchantId))
{
return new ValidationResult(ErrorMessage);
}
else
{
return ValidationResult.Success;
}
}
}
我的商户回购始终为空。
编辑:
这是我的视图模型的一部分
public class MerchantCreationModel
{
[Required]
[MerchantMustBeUnique(ErrorMessage = "Already exists!")]
public int? NewMerchantId { get; set; }
}
Autofac注册
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterFilterProvider(); // Inject properties into filter attributes
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MerchantRepo>().As<IMerchantRepo>().PropertiesAutowired();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
我在ASP.NET MVC中使用DependencyResolver
类解决了问题。
IMerchantRepo repo = DependencyResolver.Current.GetService<IMerchantRepo>();
我以一种不会在这个答案中乱丢代码的方式解决了这个问题,使人们能够写:
class MyModel
{
...
[Required, StringLength(42)]
[ValidatorService(typeof(MyDiDependentValidator), ErrorMessage = "It's simply unacceptable")]
public string MyProperty { get; set; }
....
}
public class MyDiDependentValidator : Validator<MyModel>
{
readonly IUnitOfWork _iLoveWrappingStuff;
public MyDiDependentValidator(IUnitOfWork iLoveWrappingStuff)
{
_iLoveWrappingStuff = iLoveWrappingStuff;
}
protected override bool IsValid(MyModel instance, object value)
{
var attempted = (string)value;
return _iLoveWrappingStuff.SaysCanHazCheez(instance, attempted);
}
}
使用一些助手类(看那边),您可以将其连接起来,例如在ASP.NET MVC中,就像在Global.asax
:-中一样
DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
typeof(ValidatorServiceAttribute),
(metadata, context, attribute) =>
new DataAnnotationsModelValidatorEx(metadata, context, attribute, true));