【发布时间】:2015-10-28 11:18:09
【问题描述】:
我正在为 ado 使用工作单元和存储库模式 - cribbed from jgauffin
我也在尝试使用 DI(ninject),但我正在努力弄清楚如何处理存储库和 UoW 的安全处置以及如何实例化它们(范围等)
public interface IUnitOfWork : IDisposable{
void SaveChanges();
SqlCommand CreateCommand();
}
public IItemRepository{
List<Item> GetForParent(int parentID);
Item GetById(int id);
bool Update(Item item);
}
如果没有 DI,我会使用它,而控制器没有特殊的构造函数:
public IHttpActionResult UpdateItem(Item item){
if(!ModelState.IsValid) return BadRequest(ModelState);
using (var uow = UnitOfWorkFactory.Create())
{
var repo = new ItemRepository(uow);
if (repo.GetByID(item.ID) == null) return NotFound();
if (!repo.Update(item)) return BadRequest("Unable to update Item");
uow.SaveChanges();
return Ok();
}
}
我是否正确地假设我应该改为执行以下操作,因为要进行保存,我需要 uow 并且即使它已经注入到存储库构造函数 public ItemRepository(IUnitOfWork uow){_unitOfWork = uow;}
控制器也需要它..
IItemRepository _repo;
IUnitOfWork _uow;
public ItemController(IItemRepository repo, IUnitOfWork uow)
{
_repo = repo;
_uow = uow;
}
public IHttpActionResult UpdateItem(Item item){
if(!ModelState.IsValid) return BadRequest(ModelState);
if (_repo.GetByID(item.ID) == null) return NotFound();
if (_repo.Update(item)){
_uow.SaveChanges();
return Ok();
}
return BadRequest("Unable to update item");
}
并确保 ninject 创建具有正确范围的工作单元
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IItemRepository>().To<ItemRepository>();
我明白这可能不是一起设置 UoW 和存储库的正确方法,并欢迎任何建议
【问题讨论】:
-
你为什么不使用
using声明来处理你的UoW?据我了解,您应该使用 UoW 包装您的存储库,完成所有必要的工作,然后提交更改并释放它。 -
我的印象是,当 Ninject 创建实例时,由它来处理它。 UoW 具体实现有一个 dispose 方法,用于处理连接并清除它正在使用的任何事务
-
好的,我看到 Ninject 处理了所有不在瞬态范围内的对象。你在哪里创建你的 UoW?从我的角度来看,您似乎正确地处理了它。
标签: c# ado.net ninject repository-pattern unit-of-work