user145610 user145610 - 20 days ago 7x
C# Question

How to pass Unity Container has constructor parameter to Constructor of Controller in Web API

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
, If the container is passed has constructor parameter, I can get reference of
. 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.


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