注册 | 登录

解决c# - How to pass Unity Container has constructor parameter to Constructor of Controller in Web API

itPublisher 分享于



I have 2 classes with same interface implementation, say Class1 and Class2 inherit from IInterface1

I need to have WEB API 2.0 Controller's Constructor to take UnityContainer has constructor parameter,

In my Bootstrapper class of Web API, I'm creating instance of container like below

public static IUnityContainer Initialise()
    container = new Lazy<IUnityContainer>(() => BuildUnityContainer());
    //Uncomment below code for MVC.
    // DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    GlobalConfiguration.Configuration.DependencyResolver = 
        new IoCContainer(container.Value);

    return container.Value;

private static IUnityContainer BuildUnityContainer()
    var container = new UnityContainer();
    return container;

I want make use of Container which has created as parameter to Controller constructor and also service layer constructor. How to pass unit container has constructor parameter to my Controller and Service layer.

I can make use of below code

GlobalConfiguration.Configuration.DependencyResolver.GetService (type)

but I don't want to do it with above code, is there a way to Container has parameter, and resolve my class based condition? For Example: Based on user input, I need to resolve Class1 or Class2, If the container is passed has constructor parameter, I can get reference of Class1 or Class2. I don't want to create new instance of Unity Container, register and resolve the class. Please let me know to handle situation like this with Web API Constructors.

c# dependency-injection unity-container web-api
  this question
edited Aug 13 '14 at 21:18 Steven 102k 13 165 259 asked Jun 4 '14 at 20:08 user145610 834 2 14 40


1 Answers


I could able to resolve by defining interfaces with names in my Botstrapper

container.RegisterType<I1, Class1>("Class1",new HierarchicalLifetimeManager());
container.RegisterType<I1, Class2>("Class2",new HierarchicalLifetimeManager());

Since I cant get reference of GlobalConfiguration.Configuration.DependecyResolver in service layer, I have make unitycontainer has constructor parameter in controller and service layer. try to resolve by their names

_serviceinstance= _unityContainer.Resolve<I1>("Class1");

I Could able to get my Class1 instance similarly for class2 also

  this answer
edited Oct 2 '16 at 19:10 Crypt32 3,335 1 9 27 answered Jun 15 '14 at 6:00 user145610 834 2 14 40









您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱