views:

314

answers:

3

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?

+2  A: 

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.

JoshBerke
+1  A: 

http://davybrion.com/blog/2009/11/integrating-your-ioc-container-with-agatha/

Ruben Bartelink
Thanks. Seems like a very similar answer as the first one. That's exactly what I ended up doing, BTW. I created my own Container class that simply wraps Windsor, and let my developers use that as a Service Locator.Where feasible, of course, I try to have them use the container only in the bootstrapping portion of the application so as to avoid taking on a container dependency everywhere, but it doesn't always work out that way. This is a legacy code situation, after all.
Craig Vermeer
A: 

As I understand your question, you want to invoke DI-enabled code from legacy code.

The best option is to keep the new library DI Friendly, but container-agnostic.

Doing this, you can provide a simple Facade the legacy code can use. No need for the legacy app to use any DI Container, and no need for the Common Service Locator.

Mark Seemann