Mvc 3/Unity 2 将依赖项注入过滤器?
我如何注入以下依赖项?
public class Authenticate : AuthorizeAttribute
{
[Dependency]
public IAuthenticate AuthenticateLibrary { get; set; }
[Dependency]
public ILibrary BaseLibrary { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
我正在使用 Unity 2 注入所有控制器。有 Unity 2 和将依赖项注入过滤器的教程吗?
How can i inject the following dependencies ??
public class Authenticate : AuthorizeAttribute
{
[Dependency]
public IAuthenticate AuthenticateLibrary { get; set; }
[Dependency]
public ILibrary BaseLibrary { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
I am using Unity 2 to inject all the controllers. Is there a tutorial for Unity 2 and injecting dependencies into filters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Brad Wilson 关于服务位置有一个很好的系列,其中包括如何创建自己的可以支持依赖项注入的过滤器提供程序:http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html(向下滚动到该部分“向过滤器添加依赖注入”)。
UnitFilterAttributeFilterProvider.cs
。
Brad Wilson has a good series on Service Location which includes how to create your own filter provider that can support dependency injection: http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html (Scroll down to the section "Adding Dependency Injection to Filters").
UnitFilterAttributeFilterProvider.cs
.
由于 Unity 没有实例化过滤器,因此无法注入它们。您将不得不求助于服务定位器模式,如下所示:
Since Unity is not instantiating the Filters, it cannot inject them. You would have to resort to service locator pattern such as in the following:
对于所有来到这里寻找 MVC4 + Unity 解决方案的人(像我一样),虽然接受的答案工作得很好,但我想补充一点,现在您也可以简单地重写
GetFilters
方法。 code>FilterAttributeFilterProvider 类:干杯。
For all people that (like me) arrived here looking for a solution in MVC4 + Unity, although the accepted answers works perfectly, I wanted to add that now you can also simply override the
GetFilters
method of theFilterAttributeFilterProvider
class:Cheers.