I was recently reading a fairly detailed comparison by Andrey Shchekin of the various injection containers out there in the .NET space. I found it interesting that the last feature he regarded as important was the ability to tell the container to mock a particular object.
Now, when I wrote an article about evaluating IoC containers, it didn’t even occur to me to include this. Now, Andrey includes many points that I haven’t covered, like the fact that Castle hasn’t had a stable release in well over a year, but on this point I think it’s best left out.
Why? Because I think that using the feature is a code smell. Certainly, I’ve injected mocks into containers before today (StructureMap 1.0 with old school Rhino Mocks, not a thing of beauty) but frankly, it was because I didn’t understand how to use containers as well as I do now.
So, how should you use them? You should inject your dependencies into the constructor, period. There’s times you need setter injection (configuring Retlang, sadly, falls into this category, so does most of Microsoft’s stuff), but I wouldn’t recommend designing that way, it vastly complicates your analysis.
You might want to dynamically reference components, but that’s why I wrote AutoGen. (As a way to tell if someone feels strongly about something, see how many weekends he’s spent on it.) Even if you don’t have something like this, you still ought to be using your own builder interface and passing that in. At the very least, you’re explicitly documenting your actual interaction with the container.
So why should you be injecting mocks into your container? Well, the only reason I can think for doing this is if you’re referring to your container statically. You shouldn’t be doing this, for any number of reasons. It doesn’t help that most of the StructureMap examples still use static paradigm, but it’s not actually a recommended method of doing it.
In short, if you are looking for the ability to inject mocks into a container, I would recommend you take a look at how you interact with the container in the first place. Chances are you’ve actually managed to use the container in a style that containers are meant to discourage.