gpt4 book ai didi

c# - 用于模拟的构造函数重载错误

转载 作者:太空狗 更新时间:2023-10-30 01:24:29 25 4
gpt4 key购买 nike

我有 3 个组件 Presenter、Business 和 DataAccess。 Presenter 引用 Business 和 Business 引用 DataAccess。

我在业务装配中有一个 CustomerBusiness 类,它有 2 个单参数构造函数。第一个构造函数仅用于测试以模拟数据访问对象。 DataAccess 程序集中的 ICustomerDataAccess。

    class CustomerBusiness()
{
private ICustomerDataAccess _data= null;

public CustomerBusiness(ICustomerDataAccess data)
{
_data = data;
}

public CustomerBusiness(string language): this(new CustomerDataAccess("language"))
{}

public void SomeOtherMethods()
{
...
}
}

在 CustomerPresenter 类中,我编写了下面的代码,该代码给出了在 Presenter 中未引用 DataAccess 程序集的错误。但我不想在 Presenter 中添加对 DataAccess 的引用。

var custBusiness = new CustomerBusiness("english")

谁能推荐什么是最好的实现方式,避免在 Presenter 中引用 DataAccess?

仅当有两个单参数构造函数时才会出现错误。当我有以下构造函数时,错误就消失了:

      public CustomerBusiness(ICustomerDataAccess data, string language)
{
_data = data;
}

public CustomerBusiness(string language): this(new CustomerDataAccess("language"))
{}

最佳答案

Can anyone recommend what is the best way to implement this, avoiding referencing DataAccess in Presenter?

我建议要么使用 IoC 容器,要么将您的依赖项一直冒泡到您的应用程序根...

你是对的——你的演示者不应该知道你的数据访问类。但是,您进入问题水域的地方是让您的“CustomerBusiness”了解并负责实例化数据访问类。您用于测试的第一个构造函数很棒 -- 唯一您应该拥有的构造函数。

然后,您应该让 Presenter 类在其构造函数中采用“CustomerBusiness”对象。然后,它可以使用 CustomerBusiness,而无需首先了解如何实例化它或如何实例化数据访问对象,甚至不知道数据访问对象的存在。

关于c# - 用于模拟的构造函数重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9198631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com