.Net - 多个 ORM 的工作单元模式解耦

Chr*_*eis 5 .net dependency-injection inversion-of-control unit-of-work decoupling

我当前的应用程序结构是:

  • 模型组装
  • 数据组装
    • 定义由 ORM 实现的存储库接口
  • ORM组装
    • 从数据组装实现存储库接口
    • 使用unity(IoC容器)来Data.IRepository<>注册ORM.GenericRepository<>
  • 业务组装
    • 引用数据和模型程序集
    • 使用 unity 来解决类型IRepository<>
  • 用户界面组装
    • 参考业务程序集

这种结构本质上将业务层与实现IRepository<T>.

这种解耦结构的好处之一是我应该能够相对轻松地替换 ORM - 例如,从实体框架迁移到 NHibernate 或仅升级现有的 ORM。我目前首先使用 EF 4.1 代码,并正在为 NHibernate 构建另一个程序集。

我正在考虑实施工作单元模式。

我读到,这种模式应该在业务层中使用(在我的数据程序集中定义接口,并在 ORM 程序集中实现,就像我对存储库模式所做的那样)。目前,所有实例化存储库都有自己的 DbContext / 会话,并且其生命周期设置为存储库的生命周期 - 这可能很糟糕 - 我的问题是我不确定是否可以实现可以使用的工作单元模式不同的 ORM(呃,更确切地说,它可能是,我只是不跟上速度)。

这是我唯一想到的事情:

在我的数据程序集中创建具有以下功能的 IUnitOfWork:object GetCurrentSession();,然后在 ORM 程序集中的存储库的构造函数中添加一个参数,并将其转换为适当的会话/DbContext(如果是 NHibernate,则为 ISession,如果是 Entity Framework,则为 DbContext)

如果有人对这种情况有所了解,我将不胜感激。

Chr*_*eis 0

我可能已经找到了解决方案(尚未尝试过):

在数据汇编中:

public interface IUnitOfWork : IDisposable
{
   void Start();
   T Current<T>();
   // IDisposable stuff
}
Run Code Online (Sandbox Code Playgroud)

在 ORM 程序集中:

public class GenericRepository<T> : IRepository<T>
    where T : PersistentEntity
{
    private ISession CurrentSession;

    public GenericRepository(IUnitOfWork uow)
    {
         CurrentSession = uow.Current<ISession>();
    }

    // other repository stuff here
}

public class NHhibernateUnitOfWork : IUnitOfWork
{
   private ISession CurrentSession;

   public void Start()
   {
      // instantiate CurrentSession
   }

   T Current<T>()
   {
      if(typeof(T) is ISession)
         return (T)CurrentSession;
      else
         return new NotImplementedException();
   }
}

// in the prism module
container.Resolve(typeof(IUnitOfWork), typeof(NHhibernateUnitOfWork));
Run Code Online (Sandbox Code Playgroud)

在业务大会中:

IUnitOfWork uow = container.Resolve<IUnitOfWork>();
using(uow.Start())
{
    IRepository custRepo = container.Resolve<IRepository<Customer>>(uow);
    // do stuff here with cust repo
}
Run Code Online (Sandbox Code Playgroud)

这只是将 IUnitOfWork 与具体实现解耦的概念证明。