我目前的申请结构是:
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/