3
votes

If I have 10 dependencies I need to inject and don't want to have 10 params in the constructor, which injection pattern should I use?

public class SomeClass
{
    private IDependency1 _dependency1;
    private IDependency2 _dependency2;
    private IDependency3 _dependency3;
    //...
}

Should I use setter method injection?

public class SomeClass
{
    private IDependency1 _dependency1;
    private IDependency2 _dependency2;
    private IDependency3 _dependency3;
    //...

    [Inject]
    public void SetDependency1(IDependency1 dependency1)
    {
        _dependency1 = dependency1;
    }
    //...
}

Or property injection?

public class SomeClass
{
    [Inject]
    public IDependency1 Dependency1 { private get; set; }
    [Inject]
    public IDependency2 Dependency2 { private get; set; }
    [Inject]
    public IDependency3 Dependency3 { private get; set; }
    //...
}

According to the Ninject wiki, write only properties like the above are considered bad practice, but isn't it the same as the setter method injection above, just less codes?

Which pattern would make the most sense for this scenario?

1

1 Answers

9
votes

Constructor injection is always the preferred way of doing dependency injection. You should only revert to property injection, when constructor injection is not possible, for instance, when dealing with dependency cycles (where A depends on B and B depends on A).

The reason you probably ask this question is, because you become uncomfortable in writing and maintain a constructor with that many arguments.

Having that many arguments is an anti-pattern (the constructor over-injection anti-pattern), but the way around this is not to fall back to property injection. In general, when having that many dependencies, the class in question does to much; it violates the Single Responsibility Principle. Having an awkward number of dependencies will actually be the least of your problems when violating the SRP. Code the violates the SRP is harder to understand, maintain, and more difficult to test. I can talk from experience. Every time I found my self uncomfortable with writing a unit test for a class, there was something wrong with my design. Besides the SRP there are four other important principles, grouped in the SOLID acronym. Follow those principles, and you'll be a happier programmer with more maintainable software.

When a class violates the SRP, in general this means it should be split up in multiple classes that each have a single responsibility. When you do this, you will see the number of dependencies go down.