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

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

问题描述

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



然而,这个调用到这个库的代码当前不是使用任何类型的依赖注入,并重构使用DI的旧代码超出了我的项目的范围。那么,在这个旧版代码中开始使用Container的最佳方法是从我的新图书馆获取实例?



如果可能,我想避免乱抛垃圾遗留代码与我选择的任何IoC容器的硬引用。由于我对DI来说比较新,所以我们可能会改变我们想要使用哪个Container的想法。



如果我包装我的容器像CodePlex上的 CommonServiceLocator 库一样,这是一个合理的方法吗?



还有其他人做了什么?

解决方案

您可以使用facade / proxy模式来隐藏从您的旧容器的DI容器。您实际上将您的遗产连接到您实现的自定义类中,该类将了解DI容器。现在,如果您修改DI,请更新您的外墙,而不是旧版代码。



我没有对Common Service Locator进行大量研究,但前提是可能是一个很好的解决方案。您可能希望将您的立面与CSL相结合,这将从您的旧版代码完全隐藏DI概念。


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.

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?

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.

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

What have other folks done?

解决方案

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.

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天全站免登陆