4

我让 Unity 在我的 ASP.NET Web API 项目中的所有控制器上运行得很好——只需使用来自 NuGet 框的默认设置。我还设法将它连接到 MVC 过滤器属性 - 但似乎不能为 ASP.NET Web API 过滤器属性做同样的事情。

如何扩展此默认实现以将依赖项注入 ActionFilterAttribute,例如...

public class BasicAuthenticationAttribute : ActionFilterAttribute
{
    [Dependency]
    public IMyService myService { get; set; }

    public BasicAuthenticationAttribute()
    {
    }
}

此过滤器使用属性应用于控制器:

[BasicAuthentication]

我很确定我需要连接 Unity 容器,以便它处理属性类的创建,但需要一些关于从哪里开始的线索,因为它不使用与 MVC 过滤器相同的扩展点。

我只是想补充一下,我尝试过的其他事情包括服务位置而不是依赖注入,但是您返回的 DependencyResolver 与您配置的不一样。

// null
var service = actionContext.Request.GetDependencyScope().GetService(typeof(IMyService));

或者

// null
var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IApiUserService));
4

1 回答 1

7

问题是 Attribute 类是由 .NET 创建的,而不是由 WebAPI 框架创建的。

在进一步阅读之前,您是否忘记使用 IApiUserService 配置 DependencyResolver?

(IUnityContainer)container;
container.RegisterType<IApiUserService, MyApiUserServiceImpl>();
...
var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IApiUserService));

我创建了一个包含我的 UnityContainer 的 App_Start\UnityConfig 类:

public class UnityConfig {
    #region Unity Container
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer() {
        return container.Value;
    }
    #endregion

    public static void Configure(HttpConfiguration config) {
        config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
    }

    /// <summary>Registers the type mappings with the Unity container.</summary>
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    private static void RegisterTypes(IUnityContainer container) {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your types here
        // container.RegisterType<IProductRepository, ProductRepository>();
        container.RegisterType<MyClass>(new PerRequestLifetimeManager(), new InjectionConstructor("connectionStringName"));
    }
}

UnityDependencyResolverPerRequestLifetimeManager来自我内化的这篇博文和 Unity.WebApi ( Project / Nuget Package )。(因为它是引导程序)

当我需要在我的其他代码中使用 UnityContainer 时,我将它传递给构造函数:

config.Filters.Add(new MyFilterAttribute(UnityConfig.GetConfiguredContainer()));
于 2013-06-25T21:00:55.710 回答