views:

266

answers:

2

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?

+3  A: 

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.

mcintyre321
Does that work because the IOC container is aware of disposable objects (i.e. objects implementing IDispose)?
Robert Harvey
Yep. autofac is my fave container for this kind of thing. the low key approach is to instantiate and dispose the container in each action using a using block
mcintyre321
+1  A: 

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

Andrey
Is there a way to do it when the controller goes out of scope, so that I don't have to repeat it for *every* controller method?
Robert Harvey
Andrey: if you wrap every action in a `using` block, your repository need not implement IDisposable. Or implement IDisposable and dont worry about wrapping the data context in using block
ram
Robert: never do this, never rely on getting out of scope. i had a serious production issue because of this. manual is always better.
Andrey
Ram: you can put CustomerRepository into using, because it doesn't implement IDisposable
Andrey