Avoiding Dependency Injection - is it possible?

Not sure if this is a good place to ask such a question and if there is anyone interested in discussing it, but anyway…


It is recommended for scenes to have no dependencies and only “If a scene must interact with an external context, experienced developers recommend the use of Dependency Injection. […] Because classes which rely on their external environment can inadvertently trigger bugs and unexpected behavior.”.

Quote is from Godot documentation in a link above.
I actually really like DI and I’ve been using it professionally for many years now, but I’m very curious why there is never a default DI solution in engines like Unity or Godot.

So the question would be: is it actually possible to avoid using Dependency Injection and still keep the code “clean” (whatever that means)?


Let’s consider this example below that in my opinion is quite hard to resolve well without using DI.

First of all, Godot recommends designing a game in a shape of a tree which I believe is a very good way. So let’s consider this kind of tree shape:

  • Game - some kind of auto-battler like Teamfight Tactics
    • Unit - we can have multiple units so as they can be spawned dynamically, units can’t access stuff that are in the Game context.
      • Weapon - let’s say that units can for some reason have multiple guns and each gun acts on its own and shots at enemies. Weapons can also be dynamically spawned so they can’t depend on neither Game nor Unit context.
    • Buffs Controller - not created dynamically, so existing in Game context. Sometimes player, can get a buff, for example “buff all fire damage by 10%”.

So now, we probably want the damage dealt by Weapon to be modified based on the buffs, however Weapon cannot access Buffs Controller if we don’t want to have a Dependency Injection.

So without DI the correct solution would go like this - write the logic related to applying a buff in the Game context. It’ll have to do two things, that are quite painful to implement and its logic actually is better fit to be near the weapon implementation. These two things are:

  1. When buff is applied, iterate over all units and for each unit, over all weapons and apply the buff to all weapons.
  2. Subscribe to an event of unit being spawned and for each unit, to an event of a weapon being spawned on a unit and then when a weapon is spawned, apply all existing buffs to it.

Both are really annoying to implement and just having DI where the weapon itself is actually asking for some interface that returns existing buffs is much easier.


Other possible solutions like using Resources or static stuff are not good because they “singletonize” the logic.

So what do you think? Is there a way to implement a solution to this problem in a better way without using DI?

1 Like