【发布时间】: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