Search code examples
c#dependency-injectioninversion-of-controlsimple-injector

Bootstrapping a list of concretes using Simple Injector


I have a class that takes in several types of Interfaces, all which inherit from interface IVehicle. I am using Simple Injector for IOC. The class I currently have looks something like this.

public class MyClass
{
    public MyClass(ICar car, IMotorcycle motorcycle)
    {              
    }
}

However, I am trying to get rid of passing each type of IVehicle and just pass in a list of IVehicle. The list containing the ICar and IMotorcycle interfaces. So my desired class would look something like this.

public class MyClass
{
    public MyClass(IEnumerable<IVehicle> vehicles)
    {

    }
}

I have the modification of the class down but I'm not sure how to bootstrap this in order for it to pass in all the IVehicles types.

I tried doing something like this in bootstrapping.

<IEnumerable<IVehicle>, List<IVehicle>>

However, in my class when I look at my list it is empty. Does anyone know how I can go about making that list be populated with my IVehicle types(ICar, IMotorcycle)?


Solution

  • The documentation states:

    Simple Injector contains several methods for registering and resolving collections of types. Here are some examples:

    // Configuration
    // Registering a list of instances that will be created by the container.
    // Supplying a collection of types is the preferred way of registering collections.
    container.RegisterCollection<ILogger>(new[] { typeof(MailLogger), typeof(SqlLogger) });
    
    [...]
    
    // Usage
    var loggers = container.GetAllInstances<ILogger>();
    

    Translated to your case this means:

    container.RegisterCollection<IVehicle>(new[] { typeof(Car), typeof(Motorcycle) });