I am reading an old code using a UnitOfWork implementation which is coded like this:
public class UnitOfWork : IUnitOfWork
{
private MainContext _context = new MainContext();
private Dictionary<string, IRepository> _repositories;
public UnitOfWork(MainContext context)
{
_context = context;
_repositories = new Dictionary<string, IRepository>();
}
public void Register(IRepository repository)
{
_repositories.Add(repository.GetType().Name, repository);
}
public void Commit()
{
_context.SaveChanges();
}
}
On the repository side, the unit of work and context is both constructor-injected. Here are 2 of those repositories:
public class RegistrationRepository : IRegistrationRepository
{
private MainContext _context = new MainContext();
private UnitOfWork _uow = new UnitOfWork();
public RegistrationRepository(IUnitOfWork uow, MainContext context)
{
_context = context;
_uow = uow;
}
// code omitted
}
public class EmployeeRepository : IEmployeeRepository
{
private MainContext _context = new MainContext();
private UnitOfWork _uow = new UnitOfWork();
public EmployeeRepository(IUnitOfWork uow, MainContext context)
{
_context = context;
_uow = uow;
}
// code omitted
}
If I understand correctly, when I inject both these repositories in a Business Logic class, they will both use the same context and so will the UnitOfWork, thus I can have transactionality when calling uow.Commit().
What I want to ask is what the uow.Register()'s purpose is? I've seen some UoW implementations that have a Commit() method with this code:
public void Commit()
{
_repositories.ToList().ForEach(x => x.Value.Submit());
}
This I understand the Register since the Commit is looping through all Repositories. But on the first example, we just SaveChanges to context so I'm not sure Register is needed.
To sum up, I have 3 questions:
What's the purpose of Register method in the UoW implementation in the top-most if I can have transaction using context.SaveChanges() without registering the repositories?
In the last example code where there is a loop through all the repository, will that really be transactional (all succeeds or all fails)?
Which is more preferred? Also can you please post what the possible implementation for Submit() would be? I saw this example in this link
Dependency injection in unit of work pattern using repositories
but the accepted answer only has Submit() defined in IRepository but in his concrete Repository, its missing.