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.
Asked
Active
Viewed 423 times
1
-
Do you need precise control of when the object is released, or is garbage collection enough? – Christopher Stevenson Jun 21 '13 at 15:17
-
@ChristopherStevenson I just need to make sure that database connections don't hang around open when no longer needed. – SlimShaggy Jun 21 '13 at 15:23
-
The Conroller class will be instantiated for each request. In turn, after the request ends the Controller object and hence the repository object will be disposed of automatically by the Garbage Collector. – Rob Jun 21 '13 at 19:16
-
@Rob It's a possible option, but given the non-deterministic nature of the GC, I don't want to keep a database connection around until the GC decides to collect the repo. So I think I'll stick with overriding the controller's Dispose method for now - that way I'll at least be sure that the object context is disposed as soon as the controller is. – SlimShaggy Jun 25 '13 at 11:01
2 Answers
0
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
}

Jonny Hughes
- 41
- 1
-
This would effectively result in per-query object context usage, but I'd like to stick with per-request since some actions make multiple calls to repository methods, and recreating the context for each of them would introduce unnecessary overhead and defeat the purpose of context's object caching. – SlimShaggy Jun 21 '13 at 19:04
0
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

Miguel Veloso
- 1,055
- 10
- 16