问题是 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"));
}
}
UnityDependencyResolver
和PerRequestLifetimeManager
来自我内化的这篇博文和 Unity.WebApi ( Project / Nuget Package )。(因为它是引导程序)
当我需要在我的其他代码中使用 UnityContainer 时,我将它传递给构造函数:
config.Filters.Add(new MyFilterAttribute(UnityConfig.GetConfiguredContainer()));