When I need to share context between repositories I tend to introduce an overloaded constructor which lets me pass in a context. It's best to wrap your context up in a nice interface though e.g.
public partial OrderContext : DbContext, IContext
{
...
}
public class OrderLineRepository : IOrderLineRepository
{
public OrderLineRepository(string connectionString)
: this(new OrderContext(connectionName))
{
}
public OrderLineRepository(IContext context)
{
this.Context = (OrderContext)context;
}
public IContext Context { get; private set; }
}
Then in your resolver you could do
public object GetService(Type serviceType)
{
if (serviceType == typeof (LabelsController)) {
var labelRepo = new LabelRepository();
var orderRepo = new OrderLineRepository(labelRepo.Context);
return new LabelsController(
new LabelService(labelRepo, orderRepo),
new OrderLineService(orderRepo)
);
}
return null;
}
Alternatively, another approach I have used in the past is to have a UnitOfWork
type class which exposes a context e.g.
public interface IUnitOfWork : IDisposable
{
public IContext Context { get; }
}
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork(string connectionString)
{
this.Context = new OrderContext(connectionString);
}
public IContext Context { get; private set; }
public void Dispose()
{
if (Context != null)
Context.Dispose();
}
}
In your scenario, I would update my repositories to have a read/write Context
property which would allow you to swap them out in your services
public List<Label> GetLabelsOrderedByCustomerId(string customerId)
{
using (var uow = new UnitOfWork(connectionString))
{
_labelRepository.Context = uow.Context;
_orderLineRepository.Context = uow.Context;
var labels = (from ol in _orderLineRepository.GetAll()
join l in _labelRepository.GetAll() on new {ol.QualityId, ol.CustomerId, ol.SerialNumber} equals
new {l.QualityId, l.CustomerId, l.SerialNumber}
where ol.OrderCustomer == customerId
select l).Distinct().ToList();
return labels;
}
}