繁体   English   中英

工作单元和依赖注入

[英]Unit Of Work and dependency Injection

我想在我的项目中实现工作单元设计模式,从本文开始 ,dbContext和所有存储库都在UnitOfWork类中初始化,并且我发现这里没有地方可以进行依赖项注入。 有没有办法使用悬垂注射或没有必要,为什么?

您可以根据需要创建DI。

public class UnitOfWork : IDisposable
{
    private ISchoolContext _context;

    public UnitOfWork(ISchoolContext context) 
    {
        _context = context;
    }    
}

然后,您也可以在控制器中以相同的方式注入工作单元。

您可以做所有这些事情,现在的问题是,就我个人而言,是否需要花哨的DI,但这取决于您和您的需求。

如果您使用的是DbContext,则这是工作单元的实现:

class UnitOfWork : IDisposable
{
   private readonly DbContext _yourDbContext; 

   public UnitOfWork(DbContext yourDbContext)
   {
      _yourDbContext = yourDbContext
   }

   public void Save()
   {
       _yourDbContext.Save();      
   }

   void Dispose()
   {       
       _yourDbContext = null;   
   }
}

public interface IUnitOfWork
{
    void Save();    
}

用途:

IUnitOfWork _uow;

_yourStudentRepository.Add(Student);
_yourAddressRepository.Add(Address);
_uow.Save();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM