IDbContext - to Dispose or Not to Dispose

Dec 3, 2012 at 11:25 PM

What is the proper lifespan of the IDbContext? Should a new database context be instantiated every time a new query to the database is executed? I have two scenarios below, which is the proper usage? Note that I am querying MS SQL as well as MySQL servers. So, I would like to know if either have any implications as far as reaching the max connections. And yes, I am calling the database on multiple threads. Are both scenarios thread safe?

Scenario A:

My repository class implements IDisposable and holds a private variable of type IDbContext. This variable gets instantiated at the constructor and disposed when the class is disposed. There is only one instance of the context in the repository.

Scenario B:

My repository class has a private method that returns a new instance of IDbContext. Whenever another method makes a call to the database, they call this method to get a new database context.

Dec 4, 2012 at 1:45 PM


scenario A and B are thread safe if you have not enabled UseTransaction or UseSharedConnection. Also if those 2 features are not enabled then you do not need to call Dispose in Scenario A and B. Disposing the DbContext is only needed when a shared connection is used. When a non-shared connection is used (which is default behavior) then FluentData creates and opens the connection just before the query is executed and closes it just after or if any exception has occurred.


Apr 29, 2013 at 4:52 PM
Edited Apr 29, 2013 at 5:26 PM
I was wondering about the DbContext usage as well. Since DbContext implemented the IDisposable interface I wrote the code with using block to make sure it will be disposed in repository.
using(IDbContext context = Context())
BTW with respect to peformance does it makes sense to make GetContext method singleton ? This maybe tricky since in some cases you do need to dispose the context.
May 6, 2013 at 7:19 PM
1) DbContext implements IDisposable however calling Dispose is only needed when using transactions or a shared connection. So if you dont use a transaction or shared connection then you dont need to use using or call dispose.
2) If you are creating a web app then the DbContext could be a singleton per request, but not a singleton for all requests (this would make the DbContext be shared across all requests/users, you dont want this).
May 6, 2013 at 10:31 PM
Edited May 6, 2013 at 10:34 PM
Thanks for the explaination. Seems like I need to do some more experiments with framework.