开发者

How do I correctly dispose a Linq to SQL DataContext in a Repository?

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

And a 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);
   开发者_如何学Python     else
            return view("NotFound");
    }
}

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.

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?


make the repository disposable and dispose of the datacontext in it's Dispose method.

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.


actually DataContext is IDisposable . You should wrap every action in controller in using(CustomerRepository _repository = new CustomerRepository()) { ... } and implement IDisposable in repository just by calling ds.Dispose()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜