Unity的PerResolveLifetimeManager for Repositories,Unit of Work和Entity Framework DBContext

时间:2013-01-21 13:23:46

标签: entity-framework .net-3.5 unity-container repository-pattern unit-of-work

我想将存储库,服务和UoW注入应用层,并将DBcontext注入UoW和存储库。

DBContext必须与UoW中的相同上下文和AppLayer中的每个存储库相同,但必须在处理applayer后处置,并且必须在每个AppLayer解析中创建新的DBContext。

Unity的DBContext类型映射配置中的PerResolveLifetimeManager是否适合这种情况?

示例:

//main
appLayer = resolve<IAppLayer>
appLayer.doSomeStuff()
appLayer.dispose()
// end main

//applayer class
public class AppLayer : IAppLayer{

  AppLayer(IRepository, IBusinesService, IUoW){...//init vbles} //ctor, dependencies injected by Unity

  public void doSomeStuff(){

    using(transactionScope){

      businessEntity = IRepository.findEntity()
      IBusinessService.modifyEntity(businessEntity) 
      IUoW.saveChanges() //works because IRepository is using the same DBContext to find the entity, so the entity is attached to the same DBContext.

    }//end using

  }//end doSomeStuff

}//end applayerclass

1 个答案:

答案 0 :(得分:2)

PerResolveLifetimeManager非常适合这种情况。我做了一个经验测试检查持久性缓存和实例哈希码。