除了 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”,请考虑非 Web 环境。
我知道我的问题几乎是关于“生命时间管理”的,但我正在寻找一种详尽的方法。