Unity Web API - 从不同的程序集注册服务

时间:2014-07-28 12:57:44

标签: c# unity-container

我使用带有统一4的web api 2。 我的解决方案包括项目A和项目B. 项目A包含一个控制器,其构造函数需要IA类型的参数。 项目B包含一个继承自IA的类名A.

我正在尝试将A注入控制器,但失败了,因为我收到的错误是控制器没有参数更少的构造函数。

这是我在WebApiCongig.cs中使用的代码:

var container = new UnityContainer();
container.RegisterTypes(
AllClasses.FromLoadedAssemblies(),
WithMappings.FromAllInterfaces,
WithName.TypeName,
WithLifetime.ContainerControlled,null,true);
config.DependencyResolver = new UnityResolver(container);

当我使用以下内容时,一切正常,但这不是我想要的,因为现在A组件知道具体的A类型,而且重点是它赢了。

container.RegisterType<IA, A>(new HierarchicalLifetimeManager());

1 个答案:

答案 0 :(得分:0)

你需要Unity WebApi的引导程序:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(*******.Web.App_Start.UnityWebApiActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(*******.Web.App_Start.UnityWebApiActivator), "Shutdown")]

namespace ********.Web.App_Start
{
    /// <summary>Provides the bootstrapping for integrating Unity with WebApi when it is hosted in ASP.NET</summary>
    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;
        }

        /// <summary>Disposes the Unity container when the application is shut down.</summary>
        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
    }
}

您可以使用Nuget,并为WebApi LINK

安装Unity Bootstrapper