DI用于存储库和工作单元模式

时间:2013-12-10 11:05:14

标签: asp.net-mvc dependency-injection unity-container repository-pattern unit-of-work

以前我已将无参数存储库注入我的MVC控制器:

ProjectRepository实施:

public class ProjectRepository : EntityFrameworkRepository<Project>, IProjectRepository
{
    public ProjectRepository()
    { }
}

UnityConfig.cs依赖解析:

container.RegisterType<IProjectRepository, ProjectRepository>();

MVC控制器:

private IProjectRepository _projectRepository { get; set; }

public ProjectController(IProjectRepository projectRepository)
{
    _projectRepository = projectRepository;
}

这很有效。

现在我已经在我的存储库类中实现了一个工作单元模式,这样我就可以对数据进行事务性更改(特别是在对多个存储库进行更改时)。

新的ProjectRepository实现在其构造函数中接受IUnitOfWork

public class ProjectRepository : EntityFrameworkRepository<Project>, IProjectRepository
{
    public ProjectRepository(IUnitOfWork unitOfWork): base(unitOfWork)
    { }
}

这意味着多个存储库可以共享相同的IUnitOfWork,并且可以使用UnitOfWork.SaveChanges()集体提交更改。

问题:

我现在如何使用依赖注入来使用IUnitOfWork实例来实例化存储库?

public ProjectController(IProjectRepository projectRepository, IUnitOfWork unitOfWork)
{
    _projectRepository = projectRepository;
    _unitOfWork = unitOfWork;
}

也可能有多个存储库注入控制器。如何使用相同的IUnitOfWork实例化这些内容?

1 个答案:

答案 0 :(得分:1)

当您注册IUnitOfWork个实例时,请使用PerResolveLifetimeManager,这将确保IUnitOfWorkIUnityContainer.Resolve内的每个依赖关系都提供相同的实例。

例如:

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>();
    }
}

这会将True输出到控制台。

有关详细信息,请参阅Understanding Lifetime Managers页面。