public class UniqueNameAttribute : ValidationAttribute
{
private const string UniqueNameViolationMessage = "This name is already taken. Please select another.";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//return somerepo.IsUniqueName(name)
//how do I get access to repo here? Tried DI with autofac but it came out as null
}
}
我正在使用依赖注入将存储库注入我的Web API。但是,似乎我无法注入ValidationAttribute。如果我尝试注入,它会出现null。我正在使用Autofac进行DI。还有其他方法可以访问我的仓库吗?
请注意,我只使用Web API,而不是MVC,所以我不能使用MVC DependencyResolver。
builder.RegisterType<MyRepository>().As<IMyRepository>().InstancePerRequest();
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); ;
答案 0 :(得分:0)
我猜你错过了这一行:
var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();
与其从IActionFilter
继承,不如从IAutofacActionFilter
继承。