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

标签 .net dependency-injection inversion-of-control unit-of-work decoupling

我目前的申请结构是:

  • 模型组装
  • 数据组装
  • 定义由 ORM 实现的存储库接口(interface)
  • ORM 组装
  • 从数据组装
  • 实现存储库接口(interface)
  • 使用统一(IoC 容器)注册 Data.IRepository<>ORM.GenericRepository<>
  • 商务组装
  • 引用数据和模型程序集
  • 使用统一来解析 IRepository<> 的类型
  • 界面组装
  • 引用商业大会

  • 这种结构从本质上将业务层与实现 IRepository<T> 的 ORM 分离。 .

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

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

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

    这是唯一想到的:

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

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

    最佳答案

    我可能已经找到了解决方案(还没有尝试过):

    在数据集合中:

    public interface IUnitOfWork : IDisposable
    {
       void Start();
       T Current<T>();
       // IDisposable stuff
    }
    

    在 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));
    

    在商务大会中:
    IUnitOfWork uow = container.Resolve<IUnitOfWork>();
    using(uow.Start())
    {
        IRepository custRepo = container.Resolve<IRepository<Customer>>(uow);
        // do stuff here with cust repo
    }
    

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

    关于.Net - 多个 ORM 的解耦工作单元模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5602421/

    相关文章:

    c# - C#中使用字符串连接时创建了多少个字符串对象

    c# - HttpContext.RequestServices.GetService<T>() 与 services.AddScope<T>()?

    c# - 除了将所有内容添加到 Startup 类之外,是否有一种强大的方法可以在 ASP.NET Core 3.1 中注册依赖项?

    dependency-injection - 对象生命周期管理和 IoC 容器

    dependency-injection - 我正在为 .net 寻找一个简单但实​​用且强大的 IOC/DI 框架

    c# - 循环地将字符串分割成锯齿状数组

    c# - VS2010 - 如何在第一次编译错误时自动停止编译

    asp.net-mvc - 简单注入(inject)器 2.6 中的 "An MVC filter provider has already been registered for a different Container instance."

    c# - CaSTLe Windsor Typed Factory 无释放不泄漏

    .net - .NET 4.0 是否存在 mdbg 托管调试器示例?