【发布时间】:2013-06-26 05:00:55
【问题描述】:
我的 ASP.NET Web API 项目中的所有控制器都运行良好的 Unity - 只需使用来自 NuGet 框的默认设置。我还设法将它连接到 MVC 过滤器属性 - 但似乎不能为 ASP.NET Web API 过滤器属性做同样的事情。
如何扩展此默认实现以将依赖项注入到 ActionFilterAttribute 中,例如...
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
[Dependency]
public IMyService myService { get; set; }
public BasicAuthenticationAttribute()
{
}
}
这个过滤器使用属性应用于控制器:
[BasicAuthentication]
我很确定我需要连接 Unity 容器,以便它处理属性类的创建,但需要一些关于从哪里开始的线索,因为它不使用与 MVC 过滤器相同的扩展点。
我只是想补充一下,我尝试过的其他事情包括服务位置而不是依赖注入,但是您返回的 DependencyResolver 与您配置的不一样。
// null
var service = actionContext.Request.GetDependencyScope().GetService(typeof(IMyService));
或者
// null
var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IApiUserService));
【问题讨论】:
标签: dependency-injection asp.net-web-api unity-container