Category nameļ¼šdisposing

Injected objects should not be disposed be the class that receives the instance

I just read Windsor: Component Burden described as a (bad) side effect but this is not how it should work.

Disposable objects should be cleanup by its creator. This is the easiest way to define the disposing responsibility!

In the mentioned article they have a situation where  A injects X into B at construction and then worry that B doesn’t dispose X. Well the reason for that is that B shouldn’t. A should dispose X when it knows for sure that X will not be used anymore. Either at the end of the application of when it knows that B is already garbage collected.

Lets start with an example by first defining X:

interface IX{
//...
}

class X : IX, IDisposable{
//...
}

Example where A is responsible for disposing X:

class A{
void Test() {
using(IDisposable x = new X()){
object b = new B(x);
//... doing cool stuff with b
}
}
}

class B{
IX _x;

public B(IX x) {
_x = x;
}

//... The cool methods of B
}

Example where B is responsible for disposing X:

abstract class A : IFactory{
void Create<T>();

void Test() {
object b = new B(this);
//... doing cool stuff with b
}
}

class B : IDisposable{
IX _x;

public C(IFactory factory) {
_x = factory.Create<IX>();
}

public Dispose() {
IDisposable d = _x as IDisposable;
if(d==null) d.Dispose();
}
}

In the example above you clearly see who’s responsible for disposing X. It’s creator cleansup and this is how it should be done everywhere in my humble opinion. If implementation is doing it in a different way then refactor your code asap to make it more readable and more maintainable.

Ofcourse these simple examples are not like the component architecture of windsor but the solution they describe there smells. If class A injects X into B at construction and B implements IDisposable then class B isn’t responsible for disposing X. A should do the cleanup so must know when X can be safely disposed. This implies that A should know something about B’s lifetime.

  • Either dispose X when the application domain shutsdown; or
  • Knows when A is garbage colllected by checking for example its weak reference; or
  • Subclassing B at runtime to implement a callback or demanding B to implement a custom interface so A can subscribe to a dispose event.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta