Reputation: 351
I have a service classes which depends on multiple other service classes.
class Service1 {
}
class Service2 {
}
class Service3 {
}
class Service4 {
}
class Service5 {
public Service5(Service1 s1, Service2 s2, Service3 s3, Service4 s4);
}
Is there a design pattern/best practices where I can avoid passing multiple services to Service5 constructor. It gets complicated when other service (service1, service2 etc), needs to invoke service5 for some execution as it can cause circular dependency.
One solution I can think of is having a ServiceCollection static class on which have getters for all services.
Upvotes: 0
Views: 88
Reputation: 131326
One solution I can think of is having a ServiceCollection static class on which have getters for all services.
Static methods to retrieve the Service
objects should be really avoided. It makes them dependencies not clearly defined and switchable from the user classes depending on.
So as alternative, you could define a factory class that provides instance methods to retrieve Service
instances.
Personally, I would use rather dependency injection to address this question. With that, you would have less boiler plate code and you would not have scattered factory method invocations in your whole code.
It gets complicated when other service (service1, service2 etc), needs to invoke service5 for some execution as it can cause circular dependency.
If you have circular dependencies in your classes instantiations, you should strongly reconsidered your actual design.
Upvotes: 1