Search code examples
c#design-patternssolid-principles

Inversion of Control on a list


I have been thinking about how Inversion of Control would work when working with lists. For example somthing like this would work fine:-

public class MyClass
{
private readonly IMyInterface _instance;

public MyClass(IMyInterface instance)
{
   _instance = instance;
}

Is the below violating the Open/Closed SOLID Design Principle, and if so how can the list be implemented using IoC like in the above example?

private readonly List<IMyInterface> _interface;

    public MyClass()
    {
        _interface= new List<IMyInterface>();
        _interface.Add(new Class1());
        _interface.Add(new Class2());
        _interface.Add(new Class3());
    }
...

What I mean here is how do I implement a list collection and pass it to the constructor using IoC?


Solution

  • There are 3 ways to archive dependency injection (DI).

    1. Constructor injection: public MyClass(List<IMyInterface> tobeInjectedList)
    2. Property injection: public List<IMyInterface> TobeInjectedList { get; set; }
    3. Method injection:

      List<IMyInterface> _injectedList;
      public void Inject(List<IMyInterface> tobeInjectedList) 
      { 
          _injectedList = tobeInjectedList; 
      }
      

    A side problem I can notice from you code is that you are excessively using the new keyword which will make you class heavily depend on a bunch of other classes, basically a maintenance nightmare. I suggest Factory design pattern to overcome this problem.

    http://www.dofactory.com/net/factory-method-design-pattern