如何注入以下依赖项?
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的教程并将依赖项注入过滤器?
答案 0 :(得分:13)
Brad Wilson在服务定位方面有一个很好的系列,其中包括如何创建可以支持依赖注入的自己的过滤器提供程序:http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html(向下滚动到“向过滤器添加依赖注入”一节)。
<强> UnitFilterAttributeFilterProvider.cs 强>
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider {
private IUnityContainer _container;
public UnityFilterAttributeFilterProvider(IUnityContainer container) {
_container = container;
}
protected override IEnumerable<FilterAttribute> GetControllerAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetControllerAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
protected override IEnumerable<FilterAttribute> GetActionAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
var attributes = base.GetActionAttributes(controllerContext,
actionDescriptor);
foreach (var attribute in attributes) {
_container.BuildUp(attribute.GetType(), attribute);
}
return attributes;
}
}
。
protected void Application_Start() {
// ...
var oldProvider = FilterProviders.Providers.Single(
f => f is FilterAttributeFilterProvider
);
FilterProviders.Providers.Remove(oldProvider);
var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);
FilterProviders.Providers.Add(provider);
// ...
}
答案 1 :(得分:9)
由于Unity没有实例化过滤器,因此无法注入它们。您将不得不求助于服务定位器模式,如下所示:
public class Authenticate : AuthorizeAttribute
{
public IAuthenticate AuthenticateLibrary { get; private set; }
public ILibrary BaseLibrary { get; private set; }
public Authenticate()
{
AuthenticateLibrary = DependencyResolver.Current.GetService<IAuthenticate>();
BaseLibrary = DependencyResolver.Current.GetService<ILibrary >();
}
...
}
答案 2 :(得分:8)
对于那些(像我一样)来到这里寻找MVC4 + Unity解决方案的人来说,虽然接受的答案完美无缺,但我想补充一点,现在你也可以简单地覆盖GetFilters
方法{ {1}}课程:
FilterAttributeFilterProvider
干杯。