Lost on the subcontinent

Distributed Agile, .NET, ThoughtLife

<December 2008>
SuMoTuWeThFrSa
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910


Navigation

Subscriptions

Post Categories



Dependency Injection and IDisposable

I have been using dependency injection as a mechanism to help shape the design of my code for a while now.  I find it to be extremely useful in helping me write highly-decoupled, easily testable, well composed software.  Dependency injection allows me to cleanly separate the creation of an object from the way it is used.  In fact, I often end up in a situation where I have as many occurrences of the new keyword as I have classes in the system.

Injecting a dependency raises some interesting questions for object disposal.  Does an object take responsibility for disposing of its dependencies?  In the pre-depedency injection world, the answer would be yes as the object both instantiates and destroys its dependencies.  However, as the depedency has a life outside of the object that uses it, it would be wrong for the object to try and dispose of it.

It is worthwhile to consider that the origins of depedency injection are in the world of container management.  There, the container is responsible for not only creating, but also for managing the lifecycle, of its components (this is the crucial difference that distinguishes containers from factories).  Hence it should be the responsibility of the container to ensure not only that the dependency is properly injected, but also that it is appropriately destroyed.  This has the advantage of centralising the disposal of your components in the same way that a factory encapsulates their creation.  It also means that you can centrally manage the sequence of their destruction (generally such a big issue in non-memory managed languages).

So, what are the implications for C#?  If a component implements IDisposable, call Dispose in your container.  One nice thing about this approach is that, as the container knows which specific instance it is instantiating, you can keep the Dispose method out of your component interface.  Implementing IDisposable is the product of the way a component is implemented .  As such, it should not be part of the component interface.  So check if you have any interfaces that implement IDisposable, and, if so, think about moving this into a container instead.

posted on Sunday, July 25, 2004 1:41 PM by exortech





Powered by Dot Net Junkies, by Telligent Systems