How does the SOLID open/closed principle fit in with Dependency Injection and dependency inversion

后端 未结 3 1654
夕颜
夕颜 2021-02-06 17:09

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

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 17:45

    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))
    

提交回复
热议问题