This is a beginner question for Unity so forgive me.
In my Unity Config I have the following that creates my database context (Entity Framework), Unit of Work, and a Repository pattern object (from reverse pocos and generic repo/uow):
container
.RegisterType<IDataContextAsync, myDbContext>(
new PerRequestLifetimeManager(),
new InjectionConstructor(new object[] { connString }))
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Contact>, Repository<Contact>>()
In Microsoft MVC, my controllers are injected with services:
public myController(IContactService contactService) {
_contactService = contactService;
}
My services are injected with repositories:
public class ContactService : Service<Contact>, IContactService
{
public ContactService( IRepositoryAsync<Contact> repository) {...}
}
Everything works well but I'm not sure how to access the Unity created Unit of Work object in the Controller to save changes: UnitOfWork.SaveChangesAsync()
Without DI, here's how to create the objects:
IRepositoryProvider repoProvider = new RepositoryProvider( new RepositoryFactories());
IDataContextAsync context = new MyDbContext();
IUnitOfWorkAsync uow = new UnitOfWork(context, repoProvider);
IRepositoryAsync contactRepo = new Repository<Contact>(context, uow);
... // database changes
uow.SaveChangesAsync(); // In the Controller
The obvious thing to do is reference a UOW in the Controller constructor function, but how would Unity use that same object for the Service, and how would the Service use it for the Repositories?