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

我正在从下方访问 CustomerRepositoryAdd 方法 class

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

Now When I call Add method of CustomerRepository class then I'm getting _database null.

Now here I'm doing Dependency Injection

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

CustomerRepository customerRepository = new CustomerRepository();

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

通过直接提供 IDatabase 具体类型,您可以 不使用 注入:

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

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

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

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

这就是依赖注入的工作方式。一旦你开始注入一次 class,你也会注入其他人,这就是你的对象依赖关系图在 运行 时间被容器解析的方式。