Reputation: 4582
I am having issues with my Transactions in that they are being escalated to a distributed transaction, which I don't want. From what I read, this is caused by opening multiple connections during the scope of the transaction. To correct this, I am re-working my code to be able to create one dbContext and pass it around to all the classes so I only have one context and hence one connection during the scope of the transaction.
My question is, how do I create one instance of the context and pass it to base class. What I posted is what I am trying to do in concept, but obviously that won't work. How can I achieve this?
private WorkOrderHeaderRepository _workOrderHeaderRepository;
private WorkOrderDetailRepository _workOrderDetailRepository;
private InventoryMgmtContext _dbContext;
#region Constructors
public ManageWorkOrdersAppServ()
: base(new WorkOrderHeaderRepository(_dbContext )) <----How pass _dbContext to base here
{
_dbContext = new InventoryMgmtContext();
_workOrderHeaderRepository = new WorkOrderHeaderRepository(_dbContext);
_workOrderDetailRepository = new WorkOrderDetailRepository(_dbContext);
}
Upvotes: 0
Views: 1051
Reputation: 660279
It is hard to say what the right thing to do here is but it sounds like you want the context to be a static field, not an instance field.
private static InventoryMgmtContext _dbContext = new InventoryMgmtContext();
public ManageWorkOrdersAppServ()
: base(new WorkOrderHeaderRepository(_dbContext ))
{
_workOrderHeaderRepository = new WorkOrderHeaderRepository(_dbContext);
_workOrderDetailRepository = new WorkOrderDetailRepository(_dbContext);
}
Yes?
The downside here is that the context stays alive forever, which might not be what you want. If that's not what you want then push the problem off to the caller:
public ManageWorkOrdersAppServ(Context dbContext)
: base(new WorkOrderHeaderRepository(dbContext ))
{
_workOrderHeaderRepository = new WorkOrderHeaderRepository(_dbContext);
_workOrderDetailRepository = new WorkOrderDetailRepository(_dbContext);
}
Make the caller pass in the appropriate context and make them manage its creation.
Also, while we're criticizing this code: .NET stl gdlns frwn on abrvs in nms, thyr hrd 2 rd. I think you meant to say InventoryManagementContext
.
Upvotes: 3