Jianwu Chen
1 min readSep 30, 2019

--

I’m on the same boat as you. I have seen so much code get obscured by the Dependency Injection Framework. Abuse of DI has become a major productivity killer in many organizations.

Solving testing or customization problem essentially is, we just need a way to replace certain dependencies at runtime. Instead of mandate injection every dependency, prewired default dependencies provides great benefits as it just simplifies the logic.

Service Locator is one of the patterns, but it’s considered as anti-pattern as your code will be coupled with specific SL API and you need a centralized registry to maintain the component mapping.

Your approach of optional parameters is one of the solutions, however, if you want to replace indirect dependencies, it’s a bit cumbersome as you have to replace the dependencies along the whole path with mocked objects.

In our practice, we employed an Injectable Factory pattern. It’s a simple factory pattern with default wiring, at the same time it allows you to replace implementation at runtime. With that, you can easily replace any dependency at any level of your dependency graph just with one line of code.
You can take a look at this blog for the details and have a try.

https://medium.com/@jianwu_23512/dependency-indirection-with-injectable-factory-d6f2f60cced1

--

--

Jianwu Chen
Jianwu Chen

Written by Jianwu Chen

Passionate Open Source Developer. ex-Ebayer, ex-Googler, ex-Linkin-er

No responses yet