How to pass class instance to base class constructor

核能气质少年 提交于 2019-12-12 03:03:45

问题


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);

    }

回答1:


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.



来源:https://stackoverflow.com/questions/16263828/how-to-pass-class-instance-to-base-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!