【问题标题】:Unity DependencyAttribute works for Controller but not FilterAttribute [duplicate]Unity DependencyAttribute 适用于 Controller 但不适用于 FilterAttribute [重复]
【发布时间】:2015-10-01 23:23:47
【问题描述】:

我已经在我的 WebAPI 项目中设置了 Unity,并且在我的一个 ApiController 中使用 DependencyAttribute 时,我可以正确注入对象。我现在尝试在 ActionFilterAttribute 中使用完全相同的方法,但它没有解析(解析为 null)。

这将解析为 null:

public class ValidateEntryAttribute : ActionFilterAttribute
{
    [Dependency]
    internal ApplicationUserManager UserManager { get; set; }
    // ...
}

这里解析为对象的一个​​实例:

public class LayoutController : BaseApiController
{
    [Dependency]
    internal ApplicationUserManager UserManager { get; set; }
}

我的 UnityConfig 看起来像这样:

container.RegisterType<IUserStore<ApplicationUser, int>, ApplicationUserStore>();
container.RegisterType<ApplicationUserManager>();

我错过了什么?

【问题讨论】:

  • Unity 不能在属性中注入东西,改变你的方法。

标签: c# asp.net asp.net-web-api dependency-injection unity-container


【解决方案1】:

您可以更改设计过滤器的方法以使其成为passive,然后在旨在读取它们的操作过滤器上使用真正的依赖注入(构造函数注入),如this IActionFilter examplethis AuthorizeAttribute example 中所示。

或者,您可以破解here 所示的框架,以在操作过滤器属性上进行属性注入。但是随后您就被属性注入以及随之而来的所有downsides 所困。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多