Trying to figure out how to keep class methods clean, follow EF's guidance of short-lived DbContexts, and use DI in WPF. Issue I'm having is implementing transactions with DI. I'm trying to figure out what the best way of handling this:
public class Repository : IRepository
{
public Repository(MyDbContext dataContext) { /* blah */ }
public void Add(BLLEntity entity) { /* blah */ }
public void GetById(int id) { /* return entity */ }
}
public class NonTransactionalAppService
{
public AppService(IRepository repo) { /* blah */ }
public AddNewAccount(Account account) // Issue: Not transactional
{
// do some stuff....
repo.Add(account);
}
}
public class TransactionalAppService
{
public TransactionalAppService(IRepositoryFactory repoFactory, DbContextFactory factory) { /* blah */ }
public AddNewAccount(Account account) // Issue: Transactional, but odd?? And requires me to create the repositories with every call.
{
using (var db = factory.Create()
{
IRepo repo = repoFactory.Create(db);
repo.Add(account);
}
}
}
So how do I handle transactions, keep DI for better unit-testing, and inject only what's needed without injecting factories everywhere?
This is for a desktop WPF app and I do not want to use a DI framework.
EF has guidance to use one DbContext per form, but how would I handle that with the Composition Root? I would assume I would need some type of FormFactory that would create a form and inject all the required dependencies to include the DbContext.
ContextFactoryas dependency instead ofDbContext, then repository will create context whenever it need and as much as requiredSaveChanges()?