How do I correctly dispose a Linq to SQL DataConte

2019-06-25 07:59发布

问题:

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

回答1:

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.



回答2:

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