Search code examples
c#architecturemediatorbusiness-logic-layerdomainservices

How do I reduce the number of constructor parameters in controllers and business layer services?


This is a re-wording of this SO post.

I found that using the mediator pattern is effective at reducing the number of parameters in my controllers.

I then began to wonder if this would be affective domain services.

But wouldn't that hide the dependencies of the service?

I remember reading somewhere that if I have a bunch of dependencies being injected, I probably have a larger domain concept that can be encapsulated in its own service. I found this to be an effective pattern.

So, how do I reduce the number of constructor parameters in the business layer services?


Solution

  • Too many constructor parameters are a code smell and typically indicate a violation of the single responsibility principle - so you need to take care of that "S" in your SOLID code base.

    A constructor parameter is a dependency. By "solving" the problem with a mediator, you will still have the same number of dependencies, just with fewer constructor parameters. You essentially move from a visible SRP code smell to a hidden SRP code smell - not really a step forward.

    Improving "too many dependencies" situations

    This blog post talks about this exact problem and supports it with an example.

    The basic approach to improve your situation is to find code that clusters around a set of dependencies and extract that code into a new service class:

    1. Analyze how dependencies interact to identify clusters of behavior.
    2. Extract an interface from these clusters.
    3. Copy the original implementation to a class that implements the new interface.
    4. Inject the new interface into the consumer.
    5. Replace the original implementation with a call the new dependency.
    6. Remove the redundant dependencies.