I'm creating my first N-Tier MVC application and I've run into a road block with how to manage multiple DbContexts
with my database first approach.
I have the following layers
Presentation
Service (WCF)
Business
Data Access
I don't want an entity framework reference in my service layer but I don't see how to create an Interface or something to manage two contexts. I have it working with a single context warpped in a IDatabaseFactory but I can't seem to find an approach to manage two.
Below is my UnitOfWork
that is created in my Service ctor but every way I look at it I'm still tied to the SiteModelContainer
, when in fact I have another context.
public class UnitOfWork : IUnitOfWork
{
private SiteModelContainer _context;
private readonly IDatabaseFactory _databaseFactory;
protected SiteModelContainer SiteContext
{
get { return _context ?? (_context = _databaseFactory.Get()); }
}
public UnitOfWork(IDatabaseFactory factory)
{
_databaseFactory = factory;
_context = _databaseFactory.Get();
}
//More code
}
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private SiteModelContainer _dataContext;
public SiteModelContainer Get()
{
return _dataContext ?? (_dataContext = new SiteModelContainer());
}
protected override void DisposeCore()
{
if (_dataContext != null)
_dataContext.Dispose();
}
}
You could create a wrapper that is generic repository across DbContexts (and utilizes the underlying ObjectContext to support this).
Here is an example I've used in the past (which also decouples your code from any direct dependency on Entity Framework).
Giving your Factory and UnitOfWork a generic type parameter might be a solution:
The
IDatabaseFactory
andIUnitWork
interfaces would also have to be generic then.You could then create Unit of Works for different contexts:
Edit:
To get rid of the dependency on EF in your service classes you could try something like this. The service only knows these three interfaces:
Here are special EF-specific implementations:
Your service would get a
IUnitOfWorkFactory
injected:When the service is created the concrete instance of the factory is injected:
Keep in mind that the hard work will be in the abstract repository and it's implementation. As soon as you don't have the EF context anymore in your service class you have to mimic a lot of methods in the repo interface supporting all necessary scenarios to manipulate the data.