如何使用Unity DI将参数传递给Web API中的Action Filter

时间:2014-05-22 02:39:01

标签: c# asp.net-web-api dependency-injection unity-container

我有一个actionfilter,用于装饰我的WebApi动作

        [ApiFilter(Api="Online")]

在我的Actionfilter中,我依赖于我的存储库类,我通过Unity注入

public class ApiFilterAttribute : ActionFilterAttribute
{
    [Dependency]
    public IOdsRepository _odsRepository { get; set; }

    public string Api { get; set; }
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {

       string apiKey=actionContext.Request.GetApiKey();
       if (Api=="...")//problem is this is always null with the Unity resolver for ApiFilterAttribute
     }

我确信我只需要调整Unity如何解决这个问题,但我不确定如何获得IOdsRepository和Api值。

这是Unity配置代码,其最后一行是如何解析存储库对象。如何更改此选项以使ApiFilter参数正确传递?

  public static class UnityWebApiActivator
    {
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        // Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution.
        // var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
        var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());

        GlobalConfiguration.Configuration.DependencyResolver = resolver;
        GlobalConfiguration.Configuration.Filters.Add((ApiFilterAttribute)resolver.GetService(typeof(ApiFilterAttribute)));

    }
}

0 个答案:

没有答案