将 IoC 容器引入旧代码 [英] Introducing an IoC Container to Legacy Code

查看:21
本文介绍了将 IoC 容器引入旧代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个新的 .NET 库供我公司内部使用,它将通过依赖注入使用 IoC.当然,如果我们使用 IoC 容器来解析实例,这个库会更容易使用.

I'm writing a new .NET library for internal use at my company that will use IoC through Dependency Injection. Naturally, this library will be much easier to use if we use an IoC Container to resolve instances.

但是,将调用此库的代码当前不使用任何类型的依赖注入,并且重构遗留代码以使用 DI 超出了我的项目的范围.那么,在此遗留代码中开始使用容器以从我的新库中获取实例的最佳方式是什么?

However, the code that will be making calls into this library does NOT currently use Dependency Injection of any sort, and refactoring the legacy code to use DI is out of scope for my project. So, what's the best way to start using a Container in this legacy code to get instances from my new library?

如果可能的话,我想避免在我选择的任何 IoC 容器的硬引用中乱扔旧代码.由于我对 DI 比较陌生,因此我们很可能会在某个时候改变我们想要使用哪个 Container 的想法.

If possible, I'd like to keep from littering said legacy code with hard references to whichever IoC container I choose. Since I'm relatively new to DI, it's somewhat likely that we'll change our mind on which Container we want to use at some point.

如果我将容器包装在 CodePlex 上的 CommonServiceLocator 库中,这是否是一种合理的方法?

If I wrap my container in something like the CommonServiceLocator library on CodePlex, would that be a reasonable approach?

其他人做了什么?

推荐答案

您可以使用外观/代理模式从旧容器中隐藏 DI 容器.您本质上是将您的遗产硬连接到您实现的自定义类,该类将了解 DI 容器.现在,如果您修改您的 DI,您将更新您的外观而不是您的遗留代码.

You can use a facade / proxy pattern to hide the DI Container from your legacy container. You are essentially hardwiring your legacy to a custom class that you implement which will know about the DI container. Now if you modify your DI you update your facades not your legacy code.

我没有对 Common Service Locator 进行大量研究,但前提是它可能是一个很好的解决方案.您可能希望将您的外观与 CSL 联系起来,这将从您的遗留代码中完全隐藏 DI 概念.

I've not done a lot of research into Common Service Locator but it's premise might be a good solution. You might want to tie your facade to the CSL, this will hide the DI concept completly from your legacy code.

这篇关于将 IoC 容器引入旧代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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