I'm using asp.net mvc, Entityframework 6 and Unity for DI scenarios.
I couldn't find out why my DbContext object are being disposed too early.
I injected the GenericWoU class into PeopleController
class. When I call the ListPerson action everything works ok however the DbContext is disposed. So if I try to edit any person of the list, the following error appears:
The operation cannot be completed because the DbContext has been disposed
how can I prevent the DbContext to be disposed so early?
Here is my Generic Unit of Work class:
public class GenericUoW : IDisposable, IGenericUoW
{
private readonly DbContext entities = null;
public Dictionary<Type, object> repositories = new Dictionary<Type, object>();
public GenericUoW(DbContext entities)
{
this.entities = entities;
}
public IRepository<T> Repository<T>() where T : class
{
if (repositories.Keys.Contains(typeof(T)) == true)
{
return repositories[typeof(T)] as IRepository<T>;
}
IRepository<T> repo = new GenericRepository<T>(entities);
repositories.Add(typeof(T), repo);
return repo;
}
public void SaveChanges()
{
entities.SaveChanges();
}
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);
}
}
Here is my GenericRepository
class:
class GenericRepository<T> : IRepository<T> where T : class
{
private readonly DbContext entities = null;
private DbSet<T> _objectSet;
public GenericRepository(DbContext _entities)
{
entities = _entities;
_objectSet = entities.Set<T>();
}
public IEnumerable<T> GetAll(Func<T, bool> predicate = null)
{
if (predicate != null)
{
return _objectSet.Where(predicate);
}
return _objectSet.AsEnumerable();
}
public T Get(Func<T, bool> predicate)
{
return _objectSet.First(predicate);
}
public void Add(T entity)
{
_objectSet.Add(entity);
}
public void Attach(T entity)
{
_objectSet.Attach(entity);
}
public void Delete(T entity)
{
_objectSet.Remove(entity);
}
}
Here is my ContainerBootstrapper class:
public class ContainerBootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
DbContext entities = new TeijonStuffEntities();
container.RegisterInstance(entities);
GenericUoW GUoW = new GenericUoW(entities);
container.RegisterInstance(GUoW);
MvcUnityContainer.Container = container;
return container;
}
}