Search code examples
c#dependency-injectioninversion-of-controlcastle-windsor

Adding a new parameter to constructor on the base class means I have to refactor all of the classes that inherit from it?


I am using Castle Windsor Inversion of Control Container.

I have found that if I need to inject a new component via the constructor on the base class, then all child classes inheriting from it need to pass that component to the base's constructor. This is expected.

But what if I have dozens of children inheriting from that base class, and dozens of unit tests instantiating those child classes. Do I really need to go through and refactor all those constructors and calls to those constructors? Am I missing a design pattern that would allow me to easily modify a base class constructor without having to then refactor all the children of that class?


Solution

  • I think a direct solution to your problem would be packing up the dependencies of the base class to a new class like BaseDependencies on which the base class depends on, in this case, you just need to add a new member to BaseDependencies if there is a new dependency for the base class. The code would be something like this:

    class Base {
    public Base(BaseDependencies d) {}
    }
    
    class BaseDependencies {
    public DependencyA {get; set;}
    public DependencyB {get; set;}
    public DependencyC {get; set;}
    }
    

    The other option might be refactoring your code to reuse logic by class composition instead of inheritance. see: https://en.wikipedia.org/wiki/Composition_over_inheritance