Previously I have had parameterless repositories being injected into my MVC controllers:
ProjectRepository
implementation:
public class ProjectRepository : EntityFrameworkRepository<Project>, IProjectRepository
{
public ProjectRepository()
{ }
}
UnityConfig.cs
dependency resolution:
container.RegisterType<IProjectRepository, ProjectRepository>();
MVC Controller:
private IProjectRepository _projectRepository { get; set; }
public ProjectController(IProjectRepository projectRepository)
{
_projectRepository = projectRepository;
}
This worked great.
Now I have implemented a Unit of Work pattern into my repository classes so that I can commit transactional changes to data (especially when changes are being made to more than one repository).
The new ProjectRepository
implementation accepts a IUnitOfWork
in its constructor:
public class ProjectRepository : EntityFrameworkRepository<Project>, IProjectRepository
{
public ProjectRepository(IUnitOfWork unitOfWork): base(unitOfWork)
{ }
}
This means that multiple repositories can share the same IUnitOfWork
and changes can be collectively committed using UnitOfWork.SaveChanges()
.
QUESTION:
How do I now use dependency injection to instantiate the repository with an instance of IUnitOfWork?
public ProjectController(IProjectRepository projectRepository, IUnitOfWork unitOfWork)
{
_projectRepository = projectRepository;
_unitOfWork = unitOfWork;
}
There could also be more than one repository injected into the controller. How can these all be instantiated with the same IUnitOfWork?
ProjectService
constructor would be injected with aIProjectRepository
and anIUnitOfWork
. How can I ensure that theIUnitOfWork
instance is then also injected into theIProjectRepository
constructor? - Dave New