简体   繁体   中英

Dependency injection using IOC (Inversion of Control)

I've Interface

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

It's implemented on

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

     }
 }

Now here I'm doing Dependency Injection

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

I'm accessing Add method of CustomerRepository from below 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

Yes, you're using the dependency injection, but you're calling the wrong constructor :

CustomerRepository customerRepository = new CustomerRepository();

Your class has an empty constructor as well, which doesn't accept an IDatabase . Hence, you don't provide it when you instantiate your class, and that's why it's null.

You could not use injection by supplying the IDatabase concrete type directly:

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

But, If you started working with DI, I'm not sure that's the path you'll want to go with.

In order for that to work properly , you can inject CustomRepository to Access and register all the dependencies via a IOC container.

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

That's the way it works with dependency injection. Once you start injecting to once class, you inject the others as well, and that is how your object dependency graph gets resolved by the container, at run-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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