Reputation: 93
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?
Upvotes: 0
Views: 1542
Reputation: 4013
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.
Upvotes: 1
Reputation: 1166
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();
Upvotes: 1