Chr*_*eis 5 .net dependency-injection inversion-of-control unit-of-work decoupling
我当前的应用程序结构是:
Data.IRepository<>注册ORM.GenericRepository<>IRepository<>这种结构本质上将业务层与实现IRepository<T>.
这种解耦结构的好处之一是我应该能够相对轻松地替换 ORM - 例如,从实体框架迁移到 NHibernate 或仅升级现有的 ORM。我目前首先使用 EF 4.1 代码,并正在为 NHibernate 构建另一个程序集。
我正在考虑实施工作单元模式。
我读到,这种模式应该在业务层中使用(在我的数据程序集中定义接口,并在 ORM 程序集中实现,就像我对存储库模式所做的那样)。目前,所有实例化存储库都有自己的 DbContext / 会话,并且其生命周期设置为存储库的生命周期 - 这可能很糟糕 - 我的问题是我不确定是否可以实现可以使用的工作单元模式不同的 ORM(呃,更确切地说,它可能是,我只是不跟上速度)。
这是我唯一想到的事情:
在我的数据程序集中创建具有以下功能的 IUnitOfWork:object GetCurrentSession();,然后在 ORM 程序集中的存储库的构造函数中添加一个参数,并将其转换为适当的会话/DbContext(如果是 NHibernate,则为 ISession,如果是 Entity Framework,则为 DbContext)
如果有人对这种情况有所了解,我将不胜感激。
我可能已经找到了解决方案(尚未尝试过):
在数据汇编中:
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 与具体实现解耦的概念证明。
| 归档时间: |
|
| 查看次数: |
1500 次 |
| 最近记录: |