I have alot of repository class which used DbContext
variable. What is the best practices to initialize this DbContext
variable?
I'm trying to do this in Base class with inheritance IDisposable
, but my application make alot of operation in one time and i got DataReader is busy error. But when i use inside this function: using(var _entities = MyDbContext.Create())
all are fine? what can be a problem and what is best way to fix it?
now my base class look like this:
public abstract class BaseRepository : IDisposable
{
protected readonly MyDbContext_entities;
public BaseRepository()
{
_entities = MyDbContext.Create();
}
#region Implement IDisposable
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
and one of my repo used get this value with constructor:
public MyRepo():base(){};
function MyDbContext.Create()
:
public static MyDbContext Create()
{
return new MyDbContext();
}
The best practice is to inject the DbContext instance into the constructor or even better to inject a
Func<DBContext>
and then you can control the lifecycle of the db context on per method basis. And you won't be needing a base class for this purpose anymore.This of course requires to use a DI Container, which is trivial in asp.net mvc.