Simple injector - IEnumerable register for abstract class implementation

I am using Simple Injector and want to know if it is possible to register / resolve a collection of classes inheriting an abstract class.

The script looks like this: I have the following abstract / concrete classes:

public abstract class Animal
    {
        public string Type { get; set; }

        public abstract string MakeSound();
    }

    public class Dog : Animal
    {
        public override string MakeSound()
        {
            return "woof";
        }
    }

    public class Cat : Animal
    {
        public override string MakeSound()
        {
            return "meow";
        }
    }

    public class Pig : Animal
    {
        public override string MakeSound()
        {
            return "oink";
        }
    }

      

Also, I have a class that needs to get IEnumerable<Animal>

and call a function MakeSound

for each animal, for example:

public class Zoo
    {
        private IEnumerable<Animal> _animals;
        public Zoo(IEnumerable<Animal> animals)
        {
            _animals = animals;
        }

        public void MakeZooNoise()
        {
            foreach (var animal in _animals)
            {
                animal.MakeSound();
            }
        }
    }

      

I would like to create a collection IEnumerable<Animal>

, preferably using container initialization, and let it be handled through Simple Injector, as there are other registrations used in these child classes (not in this case, but in a real example).

Note: if there are ideas for alternative approaches, this is also welcome!

+3


source to share


1 answer


container.RegisterCollection<Animal>(new[] {
    typeof(Cat), 
    typeof(Dog), 
    typeof(Pig)
});

// or using Auto-Registration
container.RegisterCollection<Animal>(new [] {
    typeof(Animal).Assembly
});

      



+4


source







All Articles