IOC - Multiple Dependency Injection

Consider below:

public class DependencyA {}
public class DependencyB {}
public class DependencyC {}
public class DependencyD {}

public class Service1
{
    public Service1(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}
public class Service2
{
    public Service2(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}
public class Service3
{
    public Service3(DependencyA a, DependencyB b, DependencyC c, DependencyD d) { ... }
}

      

I find that many of my services depend on a few common components and I am thinking of implementing a catch solution as shown below (all connected via Windsor) to keep the code repeating in the service constructors.

public class DependencyContainer
{
    public DependencyA A { get; set; }
    public DependencyB B { get; set; }
    public DependencyC C { get; set; }
    public DependencyD D { get; set; }
}

public class Service1
{
    public Service1 (DependencyContainer container) { ... }
}

      

Alternatively, I could create a ServiceBase class.

public class ServiceBase
{
    public DependancyA A { get; set; }
    public DependancyB B { get; set; }
    public DependancyC C { get; set; }
    public DependancyD D { get; set; }
}

public class Service1 : ServiceBase {}

      

The real question is, does this highlight the broader design problem in services?

I may be taking DI too far, but these are all genuine dependencies.

If so, how should I code this? If not, is the proposed solution an acceptable way to achieve this goal?

0


a source to share


2 answers


Too many dependencies on your services can show that your service is doing too many things. In other words, it probably violates the single responsibility principle.



+1


a source


It's hard to talk about the problem without the broader context, but you may be dealing with too fine-grained dependencies. Are the four relationships related? Do they make sense as a whole?

If so, your approach is very important.



If not, you can hit the wall in your architecture. You may have partitioned your domain in such a way that responsibilities that should be placed on one or more (implicitly existing) objects are tied to other objects. In this case, you should look into your domain and try to identify these duplicate implicit entities, make them explicit, and move the behavior into them. This is, however, much more complex and very specific to your domain and application.

And it has nothing to do with IoC

+1


a source







All Articles