在 Rob Conery 风格的 ASP.NET MVC 应用程序中,您通常有一个存储库:

public class CustomerRepository
{
    DataContext dc = new DataContext();

    public IQueryable<Customer> AllCustomers()
    {
        return db.Customers;
    }

    public Customer GetCustomer(int customerID)
    {
        return db.Customers.FirstOrDefault(c => c.CustomerID = customerID);
    }
}

和一个 Controller :
public class CustomerController: Controller
{
    CustomerRepository _repository;

    public ActionResult Index()
    {
        var data = _repository.AllCustomers();
        return view("Index", data);
    }

    public ActionResult Details(int id)
    {
        var data = _repository.GetCustomer(id);
        if (data !=null)
            return view("Details", data);
        else
            return view("NotFound");
    }
}

当请求通过路由引擎路由到 Controller 时, Controller 通过 ASP.NET MVC 核心引擎中的 Controller 工厂实例化。然后它在 Controller 上执行适当的方法。

假设我想在 DataContext 中实现 IDisposable,如何正确地对 DataContext 进行 Dispose,而不必为存储库中的每个方法重新实例化 DataContext?

最佳答案

使存储库可丢弃并在其 Dispose 方法中处理数据上下文。

如果您想知道谁处理了 repo,Rob 可能会使用 IOC 容器,该容器将 repo 注入(inject) Controller ,每个请求都有一个实例,并会在请求结束时自动处理 repo。

关于c# - 如何在存储库中正确处理 Linq to SQL DataContext?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2357615/

10-09 08:38
查看更多