Dependency injecting an IEnumerable of generic abstract class

Welcome to the world of covariance and contravariance. While IEnumerable<T> is covariant, your Base<T> class isn’t, because classes can’t have any variance applied to them. Only interfaces and delegates can. This means that the following code does not compile:

Base<BaseDetails> b = new A();

This code above is an important exercise to do, because when it comes to generics, DI Containers can easily cause you to be mislead in thinking that the problem is in the DI Container. Always try to reconstruct the problem by hand-wiring your object graphs without the use of the DI Container. For instance:

IEnumerable<Base<BaseDetails>> _baseClasses = new Base<BaseDetails>[]
{
    new A(), // <- compile error here
    new B(), // <- compile error here
};

Again, this code will not compile in C#:

CS0029 Cannot implicitly convert type ‘A’ to ‘Base’

To make this work, you will have to change Base<T> to an interface and make its T generic argument covariant:

public interface Base<out T> { }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top