使用 StructureMap 时传递构造函数参数 [英] Passing constructor arguments when using StructureMap
问题描述
我的 DI 使用 StructureMap.想象一下,我有一个类需要 1 个参数,例如:
I'm using StructureMap for my DI. Imagine I have a class that takes 1 argument like:
public class ProductProvider : IProductProvider
{
public ProductProvider(string connectionString)
{
....
}
}
当我获得 IProductProvider 的实例时,我需要指定connectionString 在运行时.
I need to specify the "connectionString at run-time when I get an instance of IProductProvider.
我已将 StructureMap 配置如下:
I have configured StructureMap as follows:
ForRequestedType<IProductProvider>.TheDefault.Is.OfConcreteType<ProductProvider>().
WithCtorArgument("connectionString");
但是,我不想在这里调用 EqualTo("something...") 方法,因为我需要一些工具来在运行时动态指定此值.
However, I don't want to call EqualTo("something...") method here as I need some facility to dynamically specify this value at run-time.
我的问题是:如何使用 ObjectFactory 获取 IProductProvider 的实例?
My question is: how can I get an instance of IProductProvider by using ObjectFactory?
目前,我有类似的东西:
Currently, I have something like:
ObjectFactory.GetInstance<IProductProvider>();
但如你所知,这行不通...
But as you know, this doesn't work...
任何建议将不胜感激.
推荐答案
我自己找到了答案!解决办法如下:
I found the answer myself! Here is the solution:
ObjectFactory.With("connectionString").EqualTo(someValueAtRunTime).GetInstance<IProductProvider>();
希望这能帮助遇到相同问题的其他人.
Hope this helps others who have come across the same issue.
这篇关于使用 StructureMap 时传递构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!