7

参考这篇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);
        }
    }

有没有更好的地方添加全局配置?

4

1 回答 1

16

出现问题是因为您将新的 MyFilterAttribute 添加到过滤器集合(即:),GlobalConfiguration.Configuration.Filters.Add(**new MyFilterAttribute()**)而不是通过 Unity 解析的实例。由于 Unity 不参与实例的创建,因此它没有注入依赖项的触发器。这应该可以通过简单地通过 Unity 解析实例来解决。例如:

GlobalConfiguration.Configuration.Filters.Add((MyFilterAttribute)resolver.GetService(typeof(MyFilterAttribute()));
于 2013-11-05T18:20:43.290 回答