如何将类实例传递给基类构造函数 [英] How to pass class instance to base class constructor

查看:103
本文介绍了如何将类实例传递给基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的交易有问题,因为它们被升级到一个我不想要的分布式事务。从我读到的,这是由于在事务范围内打开多个连接引起的。为了纠正这一点,我正在重新编写代码,以便能够创建一个dbContext并将其传递给所有的类,所以我只有一个上下文,因此在事务范围内有一个连接。

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

    }


推荐答案

很难说在这里做的正确的事情是,但它听起来像你想要的上下文是一个静态字段,而不是一个实例字段

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

}

是?

这里的缺点是上下文永远活着,这可能不是你想要的。如果这不是你想要的,那么将问题推送给调用者:

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.

此外,当我们批评这个代码:.NET stl gdlns crwn on abrvs in nms,thyr hrd 2 rd。我想你的意思是说 InventoryManagementContext

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.

这篇关于如何将类实例传递给基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆