使用根参数构建依赖链
我有以下依赖链:
Handler() [depends on]--> Repository(string connectionString)
所以,我有一个 IHandler,它依赖于 IRepository,而 IRepository 又需要一个连接字符串。连接字符串是动态的,并且在运行时传递(因此无法从配置文件等中读取)
想象一下系统使用以下代码创建处理程序:
var handler = ObjectFactory.GetInstance<IHandler>();
这会失败,因为存储库依赖项(连接字符串)无法被使满意。我的下一个想法是使用 StructureMap 的 ExplicitArguments 在依赖链构造开始时提供参数,即:
var arguments = new ExplicitArguments();
arguments.SetArg("connectionString", "SOME CONNECTION STRING");
var handler = ObjectFactory.GetInstance<IHandler>(arguments);
这会失败,因为 StructureMap 现在期望在 Handler 中找到一个 ConnectionString 依赖项(如果有一个,则不会将这些参数传递给无论如何,存储库构造函数)。
问题是:有没有一种方法可以通过在其顶部提供参数并让 StructureMap 确定存储库需要 connectionString 参数来构造此链?
I the following dependency chain:
Handler() [depends on]--> Repository(string connectionString)
So, I have an IHandler which depends on the IRepository which in turn requires a connection string. The connection string is dynamic and is passed during runtime (so it can't be read from a config file etc.)
Imagine the system creates the handler with the following code:
var handler = ObjectFactory.GetInstance<IHandler>();
This fails because the Repository dependency (the connectionString) can't be satisfied. My next idea was to use StructureMap's ExplicitArguments to supply arguments at the start of the dependency chain construction, i.e:
var arguments = new ExplicitArguments();
arguments.SetArg("connectionString", "SOME CONNECTION STRING");
var handler = ObjectFactory.GetInstance<IHandler>(arguments);
This fails because StructureMap now expects to find a connectionString dependency in Handler (and if it has one, doesn't pass those arguments down to the Repository constructor anyway).
The question is: Is there a way to construct this chain by supplying arguments at the top of it and letting StructureMap figure out that the repository needs the connectionString argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您对
Repository
有影响力,我建议您更改构造函数以需要IConnectionStringProvider
,并使用您的对象工厂注册实现该接口的类的实例。If you have influence on the
Repository
I suggest you change the constructor to require aIConnectionStringProvider
and register an instance of a class implementing that interface with your object factory.