繁体   English   中英

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

[英]Can I call this a dependency 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对象时?

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM