工作单元,实体框架DBContext范围

Nei*_*sey 6 entity-framework unit-of-work repository-pattern

我遇到了一个问题,EF寻找这个问题的最佳实践:

public void TestEntityFramework_UOWImplementation()
{
    using (UnitOfWorkInventory uow = new UnitOfWorkInventory())
    {
        IMaterialRepository repos = new MaterialRepository(uow);

        Material mat = GetMaterial("Mikes Material", 1);

        mat.CostPrice = 20;

        repos.InsertOrUpdate(mat);

        uow.Commit();
    }
}

private Material GetMaterial(string sku, int clientId)
{
    IMaterialRepository repos = new MaterialRepository(new UnitOfWorkInventory();

    return repos.Find(sku, clientId);

}
Run Code Online (Sandbox Code Playgroud)

在TestEntityFramework_UOWImplementation()方法中,它很好,我调用为我的工作单元创建一个范围..并在其中创建一个存储库.

但是,当我想getMaterials()如下所示..我无法访问工作单元或存储库,除非我实际将其作为参数传递!这显然不是特别好.

人们如何解决这个问题?

提前致谢!

尼尔

Nei*_*sey 0

如果有人正在寻找解决这个问题的方法,我做了一些不同的事情。

我使用依赖注入框架 (StructureMap) 来处理所有 DI,因此每次实例化存储库时,它都会从 StructureMap 的服务定位器中检索 DBContext。我还将 dbcontext 范围设置为来自网络服务器的请求的持续时间。

这里的优点是,每次我检索或注入 DBContext 时,它都会在请求期间检索相同的上下文,这意味着我可以在多个方法和类中使用它!我将接口类型作为通用参数传递给构造函数,这意味着我可以将存储库指向不同的上下文。对于有大量 dbcontext 的应用程序很有帮助。

回购构造函数例如:

public class PurchaseOrderRepository<TDbContext> : GenericRepository<PurchaseOrder>, IPurchaseOrderRepository<TDbContext> where TDbContext : DbContext
{

        public PurchaseOrderRepository()
            : base((TDbContext)ObjectFactory.GetInstance<TDbContext>())
        {
        }
}   
Run Code Online (Sandbox Code Playgroud)

用法:

 //resolves the request scope InventoryContext... 
var pRepos = new PurchaseOrderRepository<IInventoryContext>();
Run Code Online (Sandbox Code Playgroud)

结构图依赖关系如下所示:

    For<IInventoryContext>().HttpContextScoped().Use<InventoryContext>();
Run Code Online (Sandbox Code Playgroud)