Skip to content
Published August 27, 2019
I have learned a LOT about the importance of dependency management since I originally wrote this rant. Really my problem was just with using a dependency injection plugin. My takeaway, 3 years later, is that plugins often suck. And that if you study SOLID architecture principles, the ‘D’ is actually Dependency Injection. It’s a pattern. Not a plugin. This rant is about a plugin. And this article does talk about it – bu this is the better route. Let’s call it Dependency Inversion going forward!
Dependency Injection in Unity is silly, and here’s why: Dependency Injection is an Inversion of Control Pattern. Unity relies on the Component Pattern, which uses the Service Locator Pattern, which is also an Inversion of Control Pattern. If you implement IoC on top of IoC, you’ve effectively made a redundant decoupling system, while simultaneously increasing code complexity. You’ve accomplished nothing but to make your code hard to trace and debug. I’ve stepped into projects where they’ve implemented some DI framework, and it’s just headache-inducing, and does nothing good. Not that I don’t make use of dependency injection, because it’s a very simple pattern to implement using just an interface and a public property. In Unity, if you want to automagically wire things up, you use the Service Locator. You use GetComponent, FindObjectOfType, and so on. Because the service locator is also compatible with Interfaces, if you design right, it’s very easy to do everything you’d do with DI. Sure, you could create a factory to create your “enemy” object and wire it up, or you could just instantiate a damn prefab, and have it locate its necessary components and services itself. tl;dr: Don’t waste your time implementing redundant top-heavy frameworks. Unity has built-in IoC.
Now… I’ve been let loose from a company because I hadn’t gotten into one of the Unity Dependency Injection. At the end of the day : I’ll use just about any approach you want, but I ran into the same thing as the guy above. DI makes it REALLY hard to debug and search through your code. And more-so, it is redundant. I need to look into how to not share namespaces / references in replacement but I think I can figure it out. Found this article : Does this fix our dependency issues? The article above describes using Composition. Fingers crossed. Update : Sept 10. Finally have some stability at the workplace. Emergency came up, figured out, and have people again that I trust. Had some time to do some reading again! Found some things that really resounded with me :

Using events is a good way to implement inversion of flow control. The class reacts to events fired from the injected classes. Injecting dependencies to register to their events is a reasonable use of injection.

Comments are closed.