【问题标题】:using Ninject with UnitOfWork and Repository (ADO not EF)将 Ninject 与 UnitOfWork 和存储库一起使用(ADO 不是 EF)
【发布时间】: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


【解决方案1】:

在我见过的其他实现中,UoW 具有访问各个存储库的方法,因此您将使用_uow.ItemRepository(或_uow.Repository&lt;MyItem&gt; 或类似的)获得存储库。这基本上是 EF 所做的:UoW 是 DbContext,它公开了类似于存储库的 DbSets。

因此,对于 DI,您将注入 UoW 而不是存储库。 (或者你会注入一个 UoW factory,你可以从中直接创建 UoW,如 using (var uow = _uowFactory.Create())...

【讨论】:

  • 关于最后一段,我更喜欢 UoW 工厂而不是 Ninject 来创建 UoW。这样,代码中的范围更清晰,更不容易出错。然后使用 Ninject 创建 UoW 工厂而不是 UoW。
猜你喜欢
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多