参考这篇CodePlex 统一文章,我能够使用 WebAPI 控制器获得过滤器属性,如下所示:
[MyFilterAttribute]
public class TestController : ApiController
{}
但是,如果我想将我的过滤器属性应用于具有 GlobalConfiguration 的所有操作,它将被剥离注入的依赖项:
public class MyFilterAttribute : ActionFilterAttribute
{
[Dependency]
public MyDependency { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (this.MyDependency == null) //ALWAYS NULL ON GLOBAL CONFIGURATIONS
throw new Exception();
}
}
public static class UnityWebApiActivator
{
public static void Start()
{
var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver = resolver;
GlobalConfiguration.Configuration.Filters.Add(new MyFilterAttribute());
RegisterFilterProviders();
}
private static void RegisterFilterProviders()
{
var providers =
GlobalConfiguration.Configuration.Services.GetFilterProviders().ToList();
GlobalConfiguration.Configuration.Services.Add(
typeof(System.Web.Http.Filters.IFilterProvider),
new UnityActionFilterProvider(UnityConfig.GetConfiguredContainer()));
var defaultprovider = providers.First(p => p is ActionDescriptorFilterProvider);
GlobalConfiguration.Configuration.Services.Remove(
typeof(System.Web.Http.Filters.IFilterProvider),
defaultprovider);
}
}
有没有更好的地方添加全局配置?