Question

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?

Was it helpful?

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.

OTHER TIPS

Dispose is never called automatically, not even by the garbage collector. If object A controls the lifecycle of object B, and if object B is disposable, object A should also be disposable and should manually call object B's Dispose method.

No, it is not redundant. It is your job to implement IDisposable on any class that has disposable members.

Your check might be redundant. You should configure the mocking to allow calls to Dispose method on your repository object, even if you implement it as a "do nothing" method for mocking.

You should take a look at Disposable Pattern

It explain you how and when to implement IDisposable and also how the Destructor and Dispose methods should be linked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top