如何在自定义ValidationAttribute中访问存储库?

时间:2015-07-23 22:57:55

标签: c# dependency-injection repository-pattern autofac

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); ;

1 个答案:

答案 0 :(得分:0)

我猜你错过了这一行:

var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();

与其从IActionFilter继承,不如从IAutofacActionFilter继承。

此处有更多详细信息:https://autofaccn.readthedocs.io/en/latest/integration/webapi.html#provide-filters-via-dependency-injection