Autofac: IEnumerable<IInterface> will always return a list of objects derive from IInterface?

Viewed 111

I inherited a fairly large codebase that makes heavy use of Autofac. I discover something interesting or even slightly puzzling.

I have a class as such

public class ClassA
{  
   public ClassA(IEnumerable<IInterface> allObjects)
   {
   }
}

And in my projects, I have a few classes that implement IInterface, such as

public class AInterface:IInterface {};
public class BInterface:IInterface {};
public class CInterface:IInterface {};

What is interesting is that if I let Autofac instantiates ClassA, then for the allObjects parameter, Autofac will give me List<IInterface>(){AInterface, BInterface, CInterface}

It seems like Autofac is going through all the types in the assemblies loaded in the app domain and automagically instantiates the classes that inherit from IInterface.

Is this a documented behavior? And if yes, where? Although this works exactly as I intended, I still want to ensure that it is documented and officially supported, so that I' don't rely on undocumented ( and hence subjected to change) behavior that works well only because of chance.

1 Answers

This behavior is documented in Implicit Relationship Types

For example, when Autofac is injecting a constructor parameter of type IEnumerable<ITask> it will not look for a component that supplies IEnumerable<ITask>. Instead, the container will find all implementations of ITask and inject all of them.

Related