如何避免传递 IOC 容器
我有一些遗留代码正在创建类的实例。
我已成功连接 IOC 容器来扫描程序集并创建它们的实例。然而,我发现在配置类中,特定的类可能会被创建多次。
该逻辑基本上循环遍历一组类类型,如果它与用户选择的类型匹配,则调用 CreateInstance
。
这很好,但我认为提供该功能的唯一方法是传递 IOC 容器并调用 Resolve,它将提供该类的新实例。
我知道这会引起严重的不满,但我不知道如何让它发挥作用。
I have some legacy code that is creating instances of classes.
I have managed to wire up an IOC container to scan assemblies and create instances of them. However, I have spotted that in a configuation class specific classes may be created numerous times.
The logic basically loops over an array of class types and if it matches the one a user selected it calls CreateInstance
.
This is fine but the only way I can think to provide that functionality is to pass the IOC Container around and call Resolve which will provide a new instance of the class.
I know this is seriously frowned upon but I can't think how to make it work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个抽象工厂,在 IOC 容器和需要新实例的代码之间提供一个抽象层,这将避免代码中充斥着容器相关的调用。
例如,当使用“Unity Application Block”时,
Func
可以用作工厂。此Func
然后隐藏容器实现,它实际上是container.Resolve()
。更新
这是一个示例:
Create an abstract factory which provides a layer of abstraction between the IOC container and the code requiring the new instances, this will avoid the code being littered with container dependent calls.
For example, when using the 'Unity Application Block',
Func<T>
can be used as a factory. ThisFunc<T>
then hides the container implementation which is actuallycontainer.Resolve<T>()
.Update
Here is an example: