I am starting to apply SOLID principles, and am finding them slightly contradictory. My issue is as follows:
My understanding of dependency inversion principle is that
Addressing the exact problem you mentioned:
You have classes that depend on IAbstraction
and you've registered an implementation with the container:
container.Register();
But you're concerned that if you change it to this:
container.Register();
then every class that depends on IAbstraction
will get AbstractionV2
.
You shouldn't need to choose one or the other. Most DI containers provide ways that you can register more than one implementation for the same interface, and then specify which classes get which implementations. In your scenario where only one class needs the new implementation of IAbstraction
you might make the existing implementation the default, and then just specify that one particular class gets a different implementation.
I couldn't find an easy way to do this with SimpleInjector. Here's an example using Windsor:
var container = new WindsorContainer();
container.Register(
Component.For().IsDefault(),
Component.For().Named("English"),
Component.For()
.DependsOn(Dependency.OnComponent(typeof(ISaysHello),"English")));
Every class that depends on ISaysHello
will get SaysHelloInSpanish
except for SaysSomething
. That one class gets SaysHelloInEnglish
.
UPDATE:
The Simple Injector equivalent is the following:
var container = new Container();
container.Register();
container.RegisterConditional(
c => c.Consumer.ImplementationType == typeof(SaysSomething));
container.RegisterConditional(
c => c.Consumer.ImplementationType != typeof(SaysSomething))