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.