我如何正确地处理一个LINQ到SQL的DataContext库中存储的? [英] How do I correctly dispose a Linq to SQL DataContext in a Repository?
问题描述
在一个罗布科纳风格的ASP.NET MVC应用程序,通常有一个存储库:
In a Rob Conery-style ASP.NET MVC application, you typically have a repository:
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);
}
}
和一个控制器:
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");
}
}
控制器被实例throught在ASP.NET MVC核心发动机控制器工厂中,当请求通过路由引擎路由到它。然后,它执行该控制器上的相应方法。
The controller is instantiated throught a Controller factory in the ASP.NET MVC core engine, when a request is routed to it through the routing engine. It then executes the appropriate method on the controller.
假设我想实施的IDisposable
在DataContext的,如何来正确的Dispose
DataContext的,而不必重新实例化的DataContext在每个库的方法?
Assuming that I want to implement IDisposable
in the DataContext, how does one properly Dispose
the DataContext, without having to re-instantiate the DataContext for every method in the repository?
推荐答案
让库一次性和处置的DataContext在它的Dispose方法。
make the repository disposable and dispose of the datacontext in it's Dispose method.
如果你想知道的回购谁作主,罗布可能会使用一个IOC容器,将注入回购到控制器与每个请求,并会自动处理的请求结束回购的实例。
If you are wondering who disposes of the repo, Rob would probably use an IOC container that would inject the repo into the controller with an instance per-request and would auto-dispose the repo at the end of the request.
这篇关于我如何正确地处理一个LINQ到SQL的DataContext库中存储的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!