Skip to main content
 首页 » 编程设计

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

2024年08月12日34fff_TT

我是依赖注入(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); 
}