Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用IOC(控制反转)的依赖项注入_C#_Interface_Dependency Injection_Nullreferenceexception - Fatal编程技术网

C# 使用IOC(控制反转)的依赖项注入

C# 使用IOC(控制反转)的依赖项注入,c#,interface,dependency-injection,nullreferenceexception,C#,Interface,Dependency Injection,Nullreferenceexception,我有界面 public interface IDatabase { void AddRow(string table, string value); } 它在 public class Database : IDatabase { public void AddRow(string table,string value) { } } 现在我正在做依赖注入 public class CustomerRepository {

我有界面

 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);
     }
}
我正在从下面的类访问
添加
方法

public class Access
{
    CustomerRepository customerRepository = new CustomerRepository();
    public void InsertRecord()
    {
        customerRepository.Add("customer", "name");
    }
}
现在,当我调用
CustomerRepository
类的
Add
方法时,我得到的是
\u数据库
null

现在我在做依赖注入

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

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

无法通过直接提供
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;
    }
}

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

当您启动
CustomerRepository
@Martiniagian时,您应该提供
IDatabase
对象。我如何向
CustomerRepository
提供
IDatabase
我的第一个问题是为什么您首先必须创建
数据库
类??您可以从
IDatabase
继承
CustomerRepository
,这对我来说有点枯燥,它只是类的分离。同意您的观点,防止有多个构造函数。现在我如何为
Access
类初始化对象。您能为
Access
class添加实现吗?@RahulNikate您有IOC容器吗?您是否使用任何外部工具进行依赖项注入?谢谢您的帮助。这真的很有帮助。你能告诉我有关国际奥委会集装箱的情况吗?如何使用IOC容器解决依赖关系?IOC容器在我的项目中,但不知道它是如何实现的。我建议你从阅读开始。依赖注入是一个非常重要的问题。非常感谢@Yuval Itzhakov对我的帮助。
public class Access
{
    private readonly CustomerRepository customerRepository;
    public Access(CustomerRepository customerRepository)
    {
        this.customerRepository = customerRepository;
    }
}