c# – 使用MVC ValidationAttribute进行Autofac属性注入
作者:互联网
我在这个问题上找到了几个问题,但没有找到一个干净简单的解决方案.
这就是我正在做的(使用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>();
标签:c,asp-net-mvc,inversion-of-control,data-annotations,autofac 来源: https://codeday.me/bug/20190624/1277204.html