【问题标题】:How do I gain access to a repository in a custom ValidationAttribute?如何访问自定义 ValidationAttribute 中的存储库?
【发布时间】:2015-07-23 22:57:54
【问题描述】:
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。如果我尝试注入,它会显示为空。我正在使用 Autofac 进行 DI。还有其他方法可以访问我的仓库吗?

请注意,我只使用 Web API,而不是 MVC,所以我不能使用 MVC DependencyResolver。

builder.RegisterType<MyRepository>().As<IMyRepository>().InstancePerRequest();

var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); ;

【问题讨论】:

  • 该问题的解决方案是使用 MVC DependencyResolver。我这里只使用 Web API。
  • 你可以试试validationContext.ServiceContainer.GetService(typeof(IService)) 吗?
  • 我尝试使用该行但收到 null。也许我错误地注册了我的类型?我已经发布了用于注册 DependencyResolver 的代码。如果很明显我是一个初学者并且正在围绕 DI 和 Autofac 进行研究,我深表歉意。
  • 没有简单的方法来做你所追求的,因为验证属性是由框架逻辑而不是你的 DI 容器实例化的。我通过显式调用验证逻辑来​​解决这个问题,如果你这样做,那么@CyrilDurand 建议的内容将在你创建自己的 ValidationContext 时起作用,它可以将任何服务注入其中。

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


【解决方案1】:

我猜你错过了这一行:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多