[英]c# unity container constructor injection with run-time value
I am using unity container XML config based constructor injection in my application. 我在我的应用程序中使用基于统一容器XML配置的构造函数注入。 I need to pass some run-time values to the constructor.
我需要将一些运行时值传递给构造函数。 Is there any way to do that without doing it in code since I am using XML configs?
自从我使用XML配置以来,有没有办法在代码中做到这一点?
eg 例如
public Calculator(DateTime businessDate)
{
_businessDate = businessDate;
}
//Calculator is instantiated using unity container and mapped in config file.
//How to pass businessDate at run-time?
Thanks!!! 谢谢!!! in advance.
提前。
What you mean by XML configs
? XML configs
是什么意思? If you are using app.config
or web.config
and your businessDate
is stored in config file then you can use system.Configuration.ConfigurationManager
class for that purpose. 如果您正在使用
app.config
或web.config
并且businessDate
存储在配置文件中,则可以使用system.Configuration.ConfigurationManager
类来实现此目的。
<AppSetting>
<add key="businessDate" value="22/12/1786">
</AppSetting>
DateTime newdt = DateTime.ParseExact(ConfigurationManager.AppSetting["businessDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);
new Calculator(newdt);
EDIT: per your comment, you can resolve this by registering the type 编辑:根据您的评论,您可以通过注册类型来解决此问题
// Register type
DateTime newdt = DateTime.ParseExact(ConfigurationManager.AppSetting["businessDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);
YourContainer.RegisterInstance<DateTime>("newdt", newdt);
YourContainer.RegisterType<Calculator>(new InjectionConstructor(YourContainer.Resolve<DateTime>("newdt")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.