Reputation:
I currently have a multi-layer MVC app (Web, BLL, DAL) and trying to understand how to correctly use dispose for DbContext.
There's a whole bunch of info on how to do it with dependency injection.
I'm not sure I will use DI (yet). Hence why I'm trying to work out if what I've done so far is correct.
Below is what has been done:
Web
In the Controller, instantiate the DbContext, and have the Dispose() method.
private MyDbContext _context = new MyDbContext();
...
...
protected override void Dispose(bool disposing)
{
if (disposing)
{
_context.Dispose();
}
base.Dispose(disposing);
}
Instantiate the BLL.service object and pass it the DbContext
BLL
Instantiate the DAL.repository object and pass it the DbContext
DAL
This class inherits from : IDisposable
And contains Dispose methods.
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
Context reason:
The controller instantiates DbContext, and it get's passed down to the repository classes. Better this way (i.e. share the context), rather than each repository instantiate their own context.
Questions:
I question if the repository classes need Dispose() logic. And what about the BLL? It has a context object, but simply passing it along? Is Dispose() logic required here.
I.e. Is the Dispose() in the controller enough? Or do is Dispose required at each level? And generally if what I've done is correct? Thanks.
Upvotes: 0
Views: 288
Reputation: 12157
I question if the repository classes need Dispose() logic. And what about the BLL? It has a context object, but simply passing it along? Is Dispose() logic required here.
Nope. Not required.
The dbContext does not hold any expensive resources to warrant its disposal (connections open for example). The dbContext closes its connection as soon as the data is retrieved. Even in high loads, the performance gain is negligible.
Issues with using Dispose() on a DbContext
Exposing the Dispose() method of the dbContext raises potential issues of the method being called in the future, effectively defeating the purpose of an ORM (unintentionally killing the lazy loader). This issue will be apparent on shared dbContexts, where one repository disposes it while some other repositories might still be using it.
Though there are certain special scenarios that you need to explicitly call the dbContext.Dispose(), but for most cases it is good enough.
Upvotes: 0