繁体   English   中英

使用IOC(控制反转)进行依赖注入

[英]Dependency injection using IOC (Inversion of Control)

我有界面

 public interface IDatabase
 {
        void AddRow(string table, string value);
 }

它实现于

 public class Database : IDatabase
 {
     public void AddRow(string table,string value)
     {

     }
 }

现在我在做依赖注入

public class CustomerRepository
{
     private readonly IDatabase _database;
     private readonly string ss;
     public CustomerRepository()
     {

     }
     public CustomerRepository(IDatabase database)
     {
        this._database = database;
     }
     public void Add(string customer,string table)
     {
        _database.AddRow(customer, table);
     }
}

我正在从下面的类访问CustomerRepository Add方法

public class Access
{
    CustomerRepository customerRepository = new CustomerRepository();
    public void InsertRecord()
    {
        customerRepository.Add("customer", "name");
    }
}

现在,当我调用CustomerRepository类的Add方法时,我将获得_database null。

现在我在做依赖注入

是的,您正在使用依赖项注入,但是您调用的是错误的构造函数

CustomerRepository customerRepository = new CustomerRepository();

您的类也有一个空的构造函数,它不接受IDatabase 因此,在实例化类时不会提供它,这就是为什么它为null的原因。

您不能通过直接提供IDatabase具体类型来使用注入:

CustomerRepository customerRepository = new CustomerRepository(new ConcreteDatabase());

但是,如果您开始使用DI,我不确定这是您要走的路。

为了使其正常工作 ,您可以注入CustomRepositoryAccess并通过IOC容器注册所有依赖项。

public class Access
{
    private readonly CustomerRepository customerRepository;
    public Access(CustomerRepository customerRepository)
    {
        this.customerRepository = customerRepository;
    }
}

这就是依赖注入的工作方式。 一旦开始注入一次类,就同时注入其他类,这就是在运行时由容器解析对象依赖图的方式。

暂无
暂无

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

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