隐藏的依赖是什么?

时间:2017-10-07 02:56:18

标签: c# dependency-injection dependencies

有人可以给我一个隐藏依赖的例子。我用谷歌搜索了它,发现了这样的结果:

  

"可见依赖项是开发人员可以从中看到的依赖项   班级的界面。如果从班级中看不到依赖关系   接口,它是一个隐藏的依赖。"

(来源 - http://tutorials.jenkov.com/ood/understanding-dependencies.html#visiblehidden

但我还是不太明白。

是否意味着在函数内部发生依赖关系,而不是在类的开头发生声明的变量?或者,当您只是创建除接口中声明的签名方法之外的函数时?

2 个答案:

答案 0 :(得分:9)

以下是隐藏依赖项的示例:

{ /* {this.renderPlayers() */ }

在上面的示例中,constructor(props){ super(props); this.setState({players: []}); } // this one } class Foo { void doSomething() //a visible method signature { //the body of this method is an implementation detail //and is thus hidden new Bar().doSomething(); } } 依赖,因为Bar依赖于Foo的协作。

隐藏,因为Foo的构造函数或Bar的方法签名中对Bar的依赖性不明确。

将一个类视为定义向协作者公开的可见合同。方法和构造函数签名是该合同的一部分。方法Foo的主体是隐藏,因为它是类中未在合同中公开的内部实现细节。我们从签名中知道的所有内容都是名为Foo的方法,其返回类型为doSomething()

对于一个反例,我们可以重构该类以使依赖关系显示出来:

doSomething()

在上面的示例中,void被明确定义为构造函数的公开签名中的依赖项。

或者我们可以这样做:

class Foo 
{
    private readonly Bar bar;

    Foo(Bar bar) //the constructor signature is visible
    {
        this.bar = bar;
    }

    void doSomething() 
    {
        bar.doSomething(); 
    }
}

现在,方法Barclass Foo { void doSomething(Bar bar) //method signature is visible { bar.doSomething(); } } 的依赖性是可见的,因为它包含在Bar的方法签名中。

答案 1 :(得分:2)

透明(具体)依赖项透明依赖项是通过公共构造函数设置的依赖项。

不透明(隐藏)依赖性不透明依赖性是未通过公共构造函数设置的依赖性,因此不容易看到该依赖性 < / p>

这里是一个示例:

// Transparent Dependency
public class StudentService
{
    private IStudentRepository _studentRepository;
    public StudentService(IStudentRepository studentRepository)
    {
        _studentRepository = studentRepository;
    }

    public List<Student> GetStudents()
    {
        return _studentRepository.GetAllStudents();
    }
}

// Opaque Dependency
public class StudentService
{
    public List<Student> GetStudents()
    {
        var _studentRepository = new StudentRepository("my-db-name");
        return _studentRepository.GetAllStudents();
    }
}

不透明依赖被认为是一种反模式,this article强调了不透明IoC的问题:

  1. 为实现Opaque IoC的组件编写测试要困难得多

  2. 透明IoC可以帮助正在“做太多事情”的身份类

Mark Seemann describes第二点很优美:

构造函数注入的奇妙好处之一是它 明显违反单一责任原则 很明显。

与此密切相关的是Nikola's 2nd law of IoC

任何具有超过3个依赖项的类都应向SRP询问 违反

相关问题