在使用StructureMap时传递构造函数参数 [英] Passing constructor arguments when using StructureMap

查看:420
本文介绍了在使用StructureMap时传递构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用StructureMap为我的DI。想象一下,我有一个类,需要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 。)方法,因为我需要一些工具在运行时动态指定这个值。

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?

目前,我有类似:

ObjectFactory.GetInstance<IProductProvider>();  

但是你知道,这不工作...

But as you know, this doesn't work...

任何建议将非常感谢。

Any advice would be greatly appreciated.

推荐答案

我自己找到答案!这里是解决方案:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆