使用Unity在两个存储库之间共享工作单元的最佳方法是什么?

时间:2012-01-25 10:40:29

标签: repository inversion-of-control unity-container unit-of-work object-lifetime

除了UnitOfWork和Repository模式之外,我想将Unity用作IoC。我阅读了各种相关文章和问题,但没有一个人完全满意我。 我对所有方法都有疑问。一个例子可以更好地解释我的问题:

我们希望在两个不同的类(可能是业务服务)中使用两个存储库,但整体工作都在一个单元中。

起始点是LocalService1.Method1方法。

public class LocalService1
{
    public void Method1(int id)
    {
        var repository1 = Container.Current.Resolve<IRepository1>(); // Injects the IUnitOfWork for the repository.
        var entity1 = repository1.GetEntity1(id);
        var service2 = Container.Current.Resolve<LocalService2>(); // Maybe it’s better not to use IoC for business logic. This is not my issue.
        service2.Method2(entity1)
    }
}
...
public class LocalService2
{
    public void Method2(Entity1 entity1)
    {
        var repository2 = Container.Current.Resolve<IRepository2>(); // Injects the IUnitOfWork for the repository.
        var count = repository2.GetEntity2sCount(entity1.Id);
        // Do some works with count and entity1
    }
}

主要问题是“在调用LocalService1.Method1时,如何在IRepository1和IRepsitory2之间共享UnitOfWork(这里可以是ObjectContext)?”。 更重要的是“我想确定UnitOfWork处理”。

我想答案会集中在这些问题上:

  • IoC配置
  • 生命时间配置
  • 处置时间(如何以及何时?)

如果您推荐使用“HttpContext”,请考虑非网络环境。

我知道我的问题几乎与“终身管理”有关,但我正在寻找一种详尽的方法。

1 个答案:

答案 0 :(得分:1)

首先:不要将Unity用作ServiceLocator。这是considered an anti-pattern。请改用constructor injection

Unity的LifetimeManagers不会自行清理。此功能位于wish list for Unity vNext

如果您希望处置对象,则应该create your own LifetimeManager和相关的 BuilderStrategy 进行清理。

TecX project(TecX.Unity.Lifetime内)中有一个样本,取自Mark Seemann的书 .NET中的依赖注入