This post originated from an RSS feed registered with .NET Buzz
by Udi Dahan.
Original Post: Dependency Injection Woes
Feed Title: Udi Dahan - The Software Simplist
Feed URL: http://feeds.feedburner.com/UdiDahan-TheSoftwareSimplist
Feed Description: I am a software simplist. I make this beast of architecting, analysing, designing, developing, testing, managing, deploying software systems simple.
This blog is about how I do it.
I've been using dependency injection techniques for some time now, and to tell you the truth, I just can't imagine going back. It brings a totally new level of decoupling to the table allowing me to reap benefits like increased testability, and decreasing numbers of bug regressions throughout all integration activities.
My tool of choice is Spring.net and all in all I'm quite pleased with it. But I do have one small gripe, I'm afraid. Its in those cases where I can't inject dependencies, or I'd rather not. For instance, say I have a UI controller that needs to open a new form as a result of something the user did. Of course I don't want the controller to be dependent on the implementation of that form, so I need to access Spring directly to ask it to give me that object like so:
IAddCustomerForm form = context.GetObject("AddCustomerForm") as IAddCustomerForm;
form.Show();
So, what don't I like?
I don't like the fact that my code needs to access that singleton "ContextRegistry" in order to get the object that implements IApplicationContext. I mean, why can't I just have it injected like any other object?
This may not seem like such a big deal, but I'd really like to keep as much of my application as possible independent of the dependency injection framework. Should I really have to muck around all my UI controllers if I want to switch frameworks? I think not.
So, I wrap Spring.
All I need is the minimalistic Abstract Factory behavior, so I define (in a separate project) an interface IFactory with a single method: "object GetObject(string id);". All my UI controllers will now depend on it, instead of the concrete ContextRegistry implementation of Spring. I then implement (in yet another separate project) IFactory with a class called Factory.Spring. In its single method, all it does is delegate the call to the code written above. Simple.
There, now I can use Spring as my dependency injection framework with out being dependent on it in my applicative code. Should I wish to migrate to the ObjectBuilder found in the CAB, it shouldn't be a big deal. Soon I'll be putting out a full example of how to use DI in the UI, as well as the use of the command pattern to further decrease coupling between views and presenters.
Which reminds me, I think that the implementation of commands in the CAB could be done a bit better, but that'll have to wait for another post.