c# - 我可以称之为依赖注入(inject)吗?

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

我是依赖注入(inject)的新手,我正在尝试弄明白。 假设我有课 book :

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 构造函数中注入(inject) Book 对象时,我可以说这是一个依赖注入(inject)吗?

最佳答案

您不会使用数据传输对象创建依赖注入(inject)。它更像是:

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

关于c# - 我可以称之为依赖注入(inject)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26863886/

相关文章:

c# - 泛型方法和匿名类型

c# - WCF maxBytesPerRead 限制为 4096

c# - 使将 CSV 字符串导入到类的列表中更容易

.net - 启动线程

c# - Azure Durable Function 中的 IoC 发生在哪里?

C#。如何在一个对象中注入(inject)多个依赖实例?

c# - 路径可视化

c# - XmlSerializer.Deserialize 可以返回 null 吗?

.net - 当某些事务正在写入同一个表时,从表中读取旧数据

Scala 依赖注入(inject) : alternatives to implicit parameters