How to dispose of repository objects in MVC3 contr

2019-05-14 19:26发布

问题:

Nearly all my controllers have a repository instantiated by initializer like this:

public class CompanyController : CtsController
{
    ICompanyRepository _repository = new CompanyRepository();

I would like to try and ensure that my repositories are always properly disposed, especially seeing as I do impersonation in them, and I believe one must be careful here. But, I don't want to have to always wrap each repository call in a new using loop in every action method.

How does MVC3 look after the lifetime and disposal of controller instances, and is it enough if I implement Disposable on them and dispose of my repos in the destructor for the controller?

回答1:

The best way to deal with this is to use Dependency Injection (also known as Inversion of Control or IOC) and a custom IControllerFactory so that your repository is created and disposed of automatically. Here is an article explaining how to do it:

Dependency Injection in ASP.NET MVC: Controllers

For MVC3, you may find some articles recommending using IDependencyResolver instead but you should be cautious of that because that interface does not have a Release callback and will cause memory leaks (dependent on which IOC container you decide to use).

If you are new to Dependency Injection, search the web for some articles on the ideas behind it.

If you don't want to switch to using IOC, then you can use a base controller that overrides the OnActionExecuted method and disposes of all IDisposables. For example:

abstract class DisposingController : Controller
{
    protected IList<IDisposable> Disposables;

    protected DisposingController()
    {
        Disposables = new List<IDisposable>();
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        foreach (var disposable in Disposables)
        {
            disposable.Dispose();
        }

        base.OnActionExecuted(filterContext);
    }
}

Then in your controller:

var myRepository = new MyRepository();
Disposables.Add(myRepository);