Search code examples
c#garbage-collectiondisposeidisposable

Does disposing an object dispose of all IDisposable properties?


This is a general question, though I do have a specific instance that I'm looking at, so I'm trying to keep the title and tags as generic as possible.

I'm doing an MVC project with IOC. My concrete Repositories implement IDisposable to dispose of the Ef Context.

Obviously, MVC handles disposing of the Controller object that gets called. However, do I need to override Dispose() in the controller? Here's my code as of right now:

private IUserRepository repository;

public UserController(IUserRepository repository) {
    this.repository = repository;
}

protected override void Dispose(bool disposing) {
    if (repository is IDisposable && repository != null) {
        (repository as IDisposable).Dispose();
        repository = null;
    }

    base.Dispose(disposing);
}

I check to make sure that it implements IDisposable as the Mocks from my Unit Tests I don't think implement it.

Now, my question is is that override of the Dispose() redundant? When the Controller (or any other object) gets disposed, does the Garbage Collector look for any properties that implements IDisposable as well, or am I doing this correctly?


Solution

  • Disposing an object doesn't automatically dispose all of its properties that are IDisposables. All it does is execute the Dispose method, what the object does then is up to the developer.

    When an object of a class is disposed it should dispose all owned resources that implement the IDisposable interface. In your case you dispose an object that could very well be still in use.

    I think the article from Stephen Cleary about IDisposable: What Your Mother Never Told You About Resource Deallocation explains about disposing objects and about the difficulties and problems that can arise in some circumstances.