Lets say you have an object called ServicesProvider which his role is to provide services. It will provide services objects such as Mailer, Logger and CacheService.
For those that tend to say it’s breaking the Single Responsibility Principle, how does it break it? Its role is only to provide services, it doesn’t do more than one thing since his responsibility is to provide services objects.
Here is the code:
public class ServicesProvider : IServicesProvider {
// Properties...
public ServicesProvider(
ICacheService cacheService,
ILoggerService loggerService,
IMailerService mailerService) { ... }
}
Is it recommended to inject this object to any business classes that need services? If not, why? What’s the recommended approach to solve this problem, please provide a complete example?
You’re aggregating all possible dependencies in a single object and then each class instead of requiring only the dependencies needed, requires an object that knows how to get all the dependencies. If you are going this root, you might as well drop the dependency injection part and just use the service locator pattern directly.
Going this way, you hide the real requirements of your classes, for example you can’t know if a class only requires
ICacheServicejust by looking at its constructor because it receives anIServiceProviderthat allows her to request any service at any point of its life cycle.As I said, what you’re trying to do is pretty similar to using the service locator pattern so you can research about the pros and cons of using dependency injection vs service locator to satisfy an inversion of control requirement.