Swi*_*oty 5 c# dependency-injection autofac repository-pattern
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
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用依赖注入将存储库注入我的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); ;
Run Code Online (Sandbox Code Playgroud)
我猜你错过了这一行:
var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();
Run Code Online (Sandbox Code Playgroud)
并且不是继承自IActionFilter,而是继承自IAutofacActionFilter。