A viable alternative to dependency injection?

In my opinion, the root cause of all the problems is not doing DI right. The main purpose of using constructor DI is to clearly state all the dependencies of some class. If something depends on something, you always have two choices: making this dependency explicit or hiding it in some mechanism (this way tends to bring more headaches than profits).

Let go through your statements:

All tests depend on the constructors.

[snip]

Problem: If I need another service in my implementation I have to modify the constructor; and that means that all of the unit tests for this class break.

Making a class depend on some other service is a rather major change. If you have several services implementing the same functionality I would argue that there is a design issue. Correct mocking and making tests satisfy SRP (which in terms of unit tests boils down to “Write a separate test per each test case”) and independent should resolve this problem.

2) Service instances get passed around unnecessarily, increasing code complexity.

One of the most general uses of the DI is to separate object creation from business logic. In you case we see that what you really need is to create some Worker which in turn needs several dependencies which are injected through the whole object graph. The best approach to resolve this issues is to never do any news in the business logic. For such cases I would prefer to inject a worker factory abstracting business code from actual creation of the worker.

I’ve contemplated using the DI framework inside the constructors instead as this resolves a couple of the problems:

public MyClass() {
  _log = Register.Get().Resolve<ILogService>();
  _blah = Register.Get().Resolve<IBlahService>();
  _data = Register.Get().Resolve<IDataService>();
}

Is there any downside to doing this?

As a benefit you will get all the downsides of using the Singleton pattern (untestable code and a huge state space of your application).

So I would say that DI should be done right (as any other tool). The solution to your problems (IMO) lies in understanding DI and education of your team members.

Leave a Comment