简体   繁体   English

工作单元和依赖注入

[英]Unit Of Work and dependency Injection

I want to implement Unit Of Work design pattern in my project and from this article the dbContext and all repositories are initialized in the UnitOfWork class , and I saw there is no place for dependency injection here . 我想在我的项目中实现工作单元设计模式,从本文开始 ,dbContext和所有存储库都在UnitOfWork类中初始化,并且我发现这里没有地方可以进行依赖项注入。 Is there is a way to use dpendency injection or there is no need and why? 有没有办法使用悬垂注射或没有必要,为什么?

You can create the DI if you want. 您可以根据需要创建DI。

public class UnitOfWork : IDisposable
{
    private ISchoolContext _context;

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

Then in your controller you can inject the Unit of Work too in the same way. 然后,您也可以在控制器中以相同的方式注入工作单元。

You can do all that stuff, now the question is if you need that fancy DI, personally I would, but that is up to you and your needs. 您可以做所有这些事情,现在的问题是,就我个人而言,是否需要花哨的DI,但这取决于您和您的需求。

Here is the implementation of unit of work if you are using DbContext : 如果您使用的是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();    
}

Uses : 用途:

IUnitOfWork _uow;

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

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

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