I have the following code in my project. Do I have to dispose the inner class explicit? If so where?
public class Outer : IDisposable
{
Context context = new Context();
Inner inner;
public Outer()
{
inner = new Inner(context);
}
public void Dispose()
{
context.Dispose();
}
}
public class Inner : IDisposable
{
Context context;
public Inner(Context context)
{
this.context = context;
}
public void Dispose()
{
context.Dispose();
}
}
Context is something like DbContext from Entity Framework.
Well, in this case you need to work out what should actually “own” the context. If you’ve got it in
Inner, do you really need it inOuteras well? Which of them really takes responsibility for them? It looks to me like you really want:Note that having made both
OuterandInnersealed, there’s no need to write a protectedDispose(bool disposing)method etc – that’s really for inheritance, which becomes a pain in general. If you really need to subclassOuterandInnerwith the possibility of needing to dispose more resources, you’ll need a more complicated implementations.Personally I try not to implement
IDisposableif possible, and keep disposable things only within local variables withusingstatements. It’s not always possible of course, but it’s worth trying…