简体   繁体   中英

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 . Is there is a way to use dpendency injection or there is no need and why?

You can create the DI if you want.

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.

Here is the implementation of unit of work if you are using 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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