What is the correct place to dispose a repository created in a custom controller factory?

432 Views Asked by At

In my ASP.NET MVC project I use a custom controller factory that instantiates an Entity Framework-based data repository and passes it to the controller's constructor. The repository object implements IDisposable, but where should I call its Dispose method? The most straightforward approach that comes to mind is to override the controller's Dispose method and do it there, but since the repository was injected into the controller and not created there, disposing it in the controller doesn't seem quite right to me.

2

There are 2 best solutions below

1
Jonny Hughes On

In your repository, you should use the Entity Framework data contexts within a using statement. This means that after the data access is finished the Dispose method will be called on the context, closing the connection.

using(var context = new MyDbContext())
{
     //do your data access
}
0
Miguel Veloso On

I guess is a little late by now, but you do it in the ReleaseController method of your IControllerFactory. Take a look at this: http://www.jasinskionline.com/technicalwiki/(S(wvw00ibwlzs5na45orv53qyl))/Custom-Controller-Factory-Putting-Controllers-in-an-External-Assembly-ASP-NET-MVC.ashx?AspxAutoDetectCookieSupport=1