我可以称之为依赖注入吗?

时间:2014-11-11 11:32:28

标签: c# .net dependency-injection code-injection

我是依赖注入的新手,我正试图弄明白。 假设我上课预订

class Book
{
    public String Author { get; set; }
    public String Title { get; set; }
    private int Quantity {get;set;}

    public Book(String aut, String pav, int qua)
    {
        this.Author = aut;
        this.Title = pav;
        this.Quantity = qua;
    }
}

然后是其他类型书

class BookWithType
{
    public Book Book { get; set; }
    public String Type { get; set; }

    public BookWithType(Book book, String type)
    {
        this.Book = book;
        this.Type = type;
    }
 }

当我在BookWithType构造函数中注入Book对象时,我可以说这是依赖注入吗?

2 个答案:

答案 0 :(得分:2)

您不会使用数据传输对象创建依赖项注入。这更像是:

public class Book
{
    public String Author { get; set; }
    public String Title { get; set; }
    public int Pages {get;set;}
    public string Type {get;set;}

    public Book(String aut, String pav, int pages, string type)
    {
        this.Author = aut;
        this.Title = pav;
        this.Pages = pages;
        this.Type = type;
    }
}

然后是某种显示层,如:

public class BookView
{
    private IBookRetriever _bookRetriever;

    public BookWithType(IBookRetriever bookRetriever)
    {
        _bookRetriever = bookRetriever;
    }
    public Book GetBookWithType(string type) {
        return _bookRetriever.GetBookOfType(type);
    }
}

IBookRetriever ......

public interface IBookRetriever {
    Book GetBookOfType(string type);
}

答案 1 :(得分:1)

依赖注入模式的目的是创建松散耦合的组件,而不依赖于其他组件。那么,直接使用具体实现有什么问题呢?嗯,问题是将来可能很难支持这样的系统。相反,当你有松散耦合的类时,很容易改变它们的行为:你只需要提供另一种抽象实现。

克里斯托斯给出了你这样做的好榜样。您的 BookWithType 类不再依赖于具体的 Book ,而是依赖于 IBook 抽象。因此,如果需要,您可以提供 IBook 的不同实现。但是,你可能不会看到从这个例子中使用DI的全部功能,因为它相当简单。取而代之的是,将数百个组件粘合在一起的巨大系统成像:如何对抗那里的复杂性?答案是使用最好的编程实践,而DI就是其中之一。

最重要的是,使用松散耦合的组件,您将获得高度可测试的系统,在哪里编写单元测试是一种乐趣:您可以轻松地提供模拟/存根等而不是具体的实现。

所以,你问题的答案是“不”。你不能称之为依赖注入(在“DI”模式的含义内)。

相关问题