【问题标题】:What is the best approache to share a UnitOfWork between two Repositories using Unity?使用 Unity 在两个存储库之间共享工作单元的最佳方法是什么?
【发布时间】:2012-01-25 10:40:28
【问题描述】:

除了 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”,请考虑非网络环境。

我知道我的问题几乎是关于“生命时间管理”的,但我正在寻找一种详尽的方法。

【问题讨论】:

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


    【解决方案1】:

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

    Unity 的 LifetimeManager 不会自行清理。这个功能在wish list for Unity vNext上。

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

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

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2014-08-28
      • 2021-04-11
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多