Simple Dependency Injection

by comfygrapes

4

Simple Dependency Injection

image

A simple Dependency Injection implementation for Godot 4 made in GDScript.

Important

  • This is a node-based dependency injection system so all the dependencies have to be nodes in the [SceneTree].
  • This tool will not create nor will it manage nodes, its job is to simply pass them to where they are needed.
  • This tool was built with simplicity in mind and working with the engine, so it can easily integrate into different workflows.

Known limitations

  1. Ensure that in an _inject function, all parameter names are the same as their corresponding dependency node name to avoid issues.

    For example, if you have a "GameManager" node and you want to receive it in a script:

    func _inject(gaem_manager: GameManager) or func _inject(gaem_manager) ❌ Fails

    func _inject(game_manager: GameManager) or func _inject(game_manager) ✅ Works

Some use cases

  1. You're in a situation where you do not have direct access (via @export) to the nodes you need in a script and do not wish to create a global singleton via autoload.
  2. You want a form of dependency inversion and wish to rely on abstractions to interact with other parts of your code.
  3. The nodes you need have their own in-scene dependencies that they need to have direct access (via @export) to.

Get Started

1. Go to Project > Project Settings > Plugins and enable the "Simple Dependency Injection" plugin.

image

2. Now there should be two new nodes in your current opened scene, for visibility, you can place them at the very top of your scene tree hierarchy.

image

3. Now click on the created [DependencyRegistrar] node and in the Inspector, click on the "Dependencies" array to expand it, click on the "Add Element" button, then assign your dependency nodes.

image image

4. Now to use it, create any node, attach any script to it, and to allow dependency injection to happen, simply create either an _inject function or a _post_inject function, or both! But do keep in mind that these are only called after _ready. (If you don't like the "_inject" or "_post_inject" function names, feel free to change them in the [DependencyProvider] script)

image

Version

1.0.1

Engine

4.4

Category

Tools

Download

Version1.0.1
Download Now

Support

If you need help or have questions about this plugin, please contact the author.

Contact Author