如何在存储库中正确处理Linq到SQL DataContext?

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

public class CustomerRepository { DataContext dc = new DataContext(); public IQueryable AllCustomers() { return db.Customers; } public Customer GetCustomer(int customerID) { return db.Customers.FirstOrDefault(c => c.CustomerID = customerID); } } 

和一个控制器:

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

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

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

使存储库处于一次性状态,并在其Dispose方法中处理datacontext。

如果你想知道是谁处理了回购,Rob可能会使用一个IOC容器,它会将repo注入到控制器中,每个请求都有一个实例,并会在请求结束时自动处理repo。

实际上DataContextIDisposable 。 您应该using(CustomerRepository _repository = new CustomerRepository()) { ... }在控制器中包装每个操作,并通过调用ds.Dispose()在存储库中实现IDisposable