Question

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?

Was it helpful?

Solution

When you register your IUnitOfWork instance, use PerResolveLifetimeManager, this will ensure every dependency of IUnitOfWork within a single IUnityContainer.Resolve gets provided the same instance.

For example:

public class SomeDependency
{

}

public class Service
{
    public Service(SomeDependency someDependency, SomeDependency someDependency2)
    {
        Console.WriteLine(someDependency == someDependency2); 
    }
}

public static void Main()
{
    using(var container = new UnityContainer())
    {
        container.RegisterType<SomeDependency>(new PerResolveLifetimeManager());
        container.Resolve<Service>();
    }
}

This will output True to the Console.

See the page for Understanding Lifetime Managers for further details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top