I am using the following UnitOfWork class in order to get repositories for my entities by using generics.
public class UnitOfWork : IUnitOfWork
{
private readonly EfDbContext _context;
public UnitOfWork()
{
_context = new EfDbContext();
}
public IRepository<T> RepositoryFor<T>() where T : Entity
{
return new Repository<T>(_context);
}
public void Save()
{
_context.SaveChanges();
}
}
However, I have run into some problems where I have two separate classes that instantiate the UnitOfWork independently for a single Entity, meaning that two repositories for that Entity are created. This causes problems with Entity Framework throwing "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" errors when I attempt save the Entity.
I am thinking that I need to more closely follow the UOW pattern as described in this post by Tom Dykstra under the "Creating the Unit of Work Class" section where the repository is stored in a private field and reused if existing or created if null. The issue that I have with this is that I want my UOW to continue using generics - Repository<T> - and not have to declare private repository fields for all the entity types I have in my code.
How might I be able to store the fact that a repository of a given type has already been instantiated and to re-use that instead of creating a new instance of it?
--- EDIT: Here's the fix ---
Using Ninject, I adjusted my bindings to only instantiate a single instance of both the repositories and UOW by specifying InRequestScope
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
//kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope(); // Removed based on comment below
kernel.Bind(typeof(EfDbContext)).ToSelf().InRequestScope();
Repository<>in the IoC container. It's a part of a Unit of Work and it shouldn't be allowed to get it somehow except from a UoW instance. Moreover, you instantiate it explicitly rather than resolve from the container. So, registering it in the container doesn't make sense. - Pavel Gatilov