Assume I have the following C# class ClassA
:
public class ClassA
{
private readonly ClassB _b;
public ClassA(ClassB b)
{
_b = b;
}
}
This class holds a reference to an instance of ClassB
, which implements IDisposable:
public class ClassB : IDisposable
{
public void Dispose()
{
// dispose
}
}
Now, I register ClassA
as a service via dependency injection, and create and pass an instance of ClassB
to it:
services.AddSingleton(service => new ClassA(new ClassB()));
At the end of the lifetime of the service, is the Dispose()
method of class B called? According to this stackoverflow post regarding the disposal of singleton instances, if ClassA
would also implement IDisposable
, then the Dispose()
method of ClassA
would also get called. Do I have to implement the interface also for ClassA
, and call the Dispose()
of ClassB
within the Dispose()
of ClassA
? Or can I somehow be assured that the Dispose()
method of ClassB
gets called without implementing IDisposable
in ClassA
?
EDIT: I marked Philip Stuyck' answer as correct, since it seems to recommend the easiest solution for this problem. As to my question Is the Dispose()
method of ClassB
ever called?, I think the discussion below clearly states that it is not called. Instead, the GC cleans up the instance of ClassB
by calling the Finalize method instead of the Dispose method on it.
If you change the way you register things to your inversion of control container then you don't have to implement idisposable at all :
services.AddSingleton<ClassB>(ClassB);
services.AddSingleton<ClassA>(ClassA);
The moment you ask for an instance of ClassA, it will look at the constructor and see that it needs classB. So you let the container resolve ClassA and don't take control of this yourself.
Then when the application closes dispose will be called as needed on ClassB
Further improvements can be done by doing inversion of control all the way and make interfaces for both classA and classB. ClassA would then contain a reference to the interface instead of the class. Which is what dependency inversion is all about.