AutoFac - Dynamic resolution of services multiple levels deep
Problem
Using the AutoFac IOC container, I have a hierarchy of services that are three layers deep.
A service in each layer is being injected with an instance of an interface in the layer below it.
The bottom layer has a single interface that has multiple implementations.
The middle layer has a single interface that has a single implementation.
The middle layer’s service is being injected with the interface in the bottom layer.
The top layer has multiple types that are injected with the single interface from the middle layer.
The problem is that depending on the service in the top layer,
I want the service in the middle layer to be injected with a different implementation of the bottom layer.
All documentation and examples for resolving different implementations of an interface are only two layers deep.
Solution
Adding a third layer, where the middle layer stays the same,
but you want the bottom layer to change based on the service in the top layer,
initially seems like a challenge, but can fortunately be solved using the same pattern prescribed for the two layer scenario.
The following is an example unit test, showing how this problem can be solved: