如何处置在MVC3控制器存储库的对象 [英] How to dispose of repository objects in MVC3 controllers

查看:143
本文介绍了如何处置在MVC3控制器存储库的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎所有我的控制器都被初始化这样的实例存储库:

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

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

我想尝试,并确保我的仓库总是妥善处置,尤其是看到我在他们做模拟,我相信我们必须要小心这里。但是,我不希望有始终包裹每个库调用在每一个动作方法一个新的使用循环。

如何生存期和处置控制器实例后MVC3看,它是不够的,如果我实现了他们的一次性和析构函数我回购处理的控制器?

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?

推荐答案

要对付这一点,最好的方法是使用依赖注入(也称为控制或IOC反转)和一个自定义IControllerFactory让您的存储库中创建和处置自动。下面是一篇文章,解释如何做到这一点:

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:

<一个href=\"http://lostechies.com/jimmybogard/2010/04/27/dependency-injection-in-asp-net-mvc-controllers/\">Dependency注射ASP.NET MVC:控制器

有关MVC3,你可能会发现一些文章用的IDependencyResolver,而不是建议,但你应该是谨慎的,因为该接口没有一个版本的回调,将导致内存泄漏(取决于​​其IOC容器您决定使用)。

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.

如果你不想切换到使用国际奥委会,那么你可以使用一个基本控制器来覆盖OnActionExecuted方法和所有IDisposables的处置。例如:

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);

这篇关于如何处置在MVC3控制器存储库的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆