ITKeyword,专注技术干货聚合推荐

注册 | 登录

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

itPublisher 分享于

2021腾讯云限时秒杀,爆款1核2G云服务器298元/3年!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1062

2021阿里云最低价产品入口+领取代金券(老用户3折起),
入口地址https://www.aliyun.com/minisite/goods

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();
    RegisterTypes(container);
    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
1

解决方法

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

 | 


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

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

如果您没有收到激活邮件,请注意检查垃圾箱。