5

我目前的申请结构是:

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

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

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

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

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

这是唯一想到的:

在我的数据程序集中创建具有函数的 IUnitOfWork: object GetCurrentSession();,然后在 ORM 程序集中的存储库的构造函数中有一个参数,并将其转换为适当的会话/DbContext(如果 NHibernate 然后是 ISession,如果是实体框架然后是 DbContext)

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

4

2 回答 2

0

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

在数据汇编中:

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 与具体实现分离的概念证明。

于 2011-04-11T16:19:06.690 回答
0

最近我做了我的研究项目,我使用工作单元和存储库模式实现了一个简单的 ASP.NET Core CRUD API。我这样做是为了让我的 API 控制器仅通过IUnitOfWork抽象与持久存储一起工作。我对 Dapper、Entity Framework Core 和 NHibernate 有单独的项目,它们每个都IUnitOfWork为特定的 ORM 实现。

这是项目链接:https ://github.com/pkirilin/UnitOfWorkExample

这是一个简单的例子:

class SomeService
{
    private readonly IAppUnitOfWork _unitOfWork;

    // IAppUnitOfWork is inherited from base IUnitOfWork and added to DI container
    public SomeService(IAppUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task DoSomethingAsync(CancellationToken cancellationToken)
    {
        var entity = await _unitOfWork.WeatherForecasts.GetByIdAsync(..., cancellationToken);
        _unitOfWork.WeatherForecasts.Delete(entity);

        var newEntity = new WeatherForecast(...);
        _unitOfWork.WeatherForecasts.Add(newEntity);

        await _unitOfWork.SaveChangesAsync(cancellationToken);
    }
}
于 2022-01-01T14:33:23.857 回答