简体   繁体   English

如何在运行时统一更新构造函数参数值

[英]How can I update a constructor parameter value in unity at run time

I have the following Unity configuration section 我有以下Unity配置部分

<register type="IDbContext" mapTo="ProjectEntities" name="ProjectEntitiesContext" >
          <constructor>
            <param name="connectionString" value="conString" />
          </constructor>

Which works great. 哪个很棒。 I get the value of "conString" in the connectionString parameter of my ProjectEntities class. 我在ProjectEntities类的connectionString参数中获得了“ conString”的值。

However, what I would like to do is change the value of the conString parameter in code. 但是,我想做的是在代码中更改conString参数的值。

some thing like 就像是

   myIocContaniner.registratons.ProjectEntities.Constructor.value = "Different Connection String"

And have "Different Connection String" passed to the ProjectEntities constructor when its created. 并且在创建时将“不同的连接字符串”传递给ProjectEntities构造函数。

The problem I am trying to solve is making a .net WebApi interact with different data bases based on the request. 我要解决的问题是根据请求使.net WebApi与不同的数据库进行交互。

I'm assuming you resolve your IDbContext every time you use it (something like this)? 我假设您每次使用IDbContext时都会解析它(类似这样)?

IDbContext myDbContext = myIocContainer.Resolve<IDbContext>("ProjectEntitiesContext");
// Some code here using myDbContext

You can just remap the type in Unity. 您可以在Unity中重新映射类型。

myIocContainer.RegisterType<IDbContext, ProjectEntities>("ProjectEntitiesContext", new InjectionConstructor("Different Connection String"));

The next time it resolves it, it'll be the new mapped type with the new injected constructor parameter. 下次解析它时,它将是具有新注入的构造函数参数的新映射类型。

This is also assuming you only have the connection string as a parameter to your constructor. 这还假设您仅将连接字符串作为构造函数的参数。 If you have other parameters, you'll need to adjust the InjectionConstructor accordingly. 如果您有其他参数,则需要相应地调整InjectionConstructor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM