↗ A Dependency Injection framework for Unity game engine.
A Unity framework to inject dependencies into your components. The project contains a simple demo game to demonstrate the framework in action.
Developed and tested with Unity 2020.3.16f1 LTS
MonoBehaviour
s (through all suitable methods named Construct
).Resolver
has a custom Inspector, which shows all dependencies of the object and specifies whether they may be fulfilled.Di
class contains convenience methods that provide access to explicit injection and object instantiation.When working on complex objects in Unity (e.g. characters in an open world game), there is frequently a need for one system of the object to reference another. For example, animation component may require a reference to a component that is responsible for vehicle entering/exiting. It may look like this:
public class VehicleEnteringAnimation : MonoBehaviour
{
public VehicleInteraction Interaction;
private void Update()
{
// do work with Interaction, e.g. react to its events
}
}
However, with this approach there are at least 2 problems:
There is an alternative approach:
public class VehicleEnteringAnimation : MonoBehaviour
{
private VehicleInteraction _interaction;
private void Update()
{
// do work with _interaction, e.g. react to its events
}
private void Awake()
{
// find the component like this:
// _interaction = GetComponentInParent<VehicleInteraction>(); // can use interfaces now!
// or this:
// _interaction = FindObjectOfType<VechileInteraction(); // but here still cannot...
}
}
This may work, but new problems have arisen:
GetComponent
callsDI Framework was created to solve exactly this problem. It supports the following notation:
public class VehicleEnteringAnimation : MonoBehaviour
{
// interaction can come from anywhere, and finally can be an interface
public void Construct(VehicleInteraction interaction)
{
_interaction = interaction;
}
private VehicleInteraction _interaction;
private void Update()
{
// do work with _interaction, e.g. react to its events
}
The final step is to add a component called Resolver
to the game object to inject the dependency. One Resolver
will take care of the game object it is attached to and of all its children.
The benefits of the approach are:
Construct
method manually to inject anything there (useful for mocking)Resolver
Resolver
)Add the following line to Packages/manifest.json
:
"com.deltation.di-framework": "https://github.com/Delt06/di-framework.git?path=Packages/com.deltation.di-framework",
GameObject
and attach a Root Dependency Container
component.Root Dependency Container
(or manually), add the other container types. For detailed info on them, refer to the section Container types.GameObject
and add a Resolver
to it. Configure the Resolver
, if needed: refer to Resolvers.Example:
Movement.cs
:using UnityEngine;
public sealed class Movement : MonoBehaviour
{
public void Construct(Rigidbody rigidbody)
{
_rigidbody = rigidbody;
}
private Rigidbody _rigidbody;
}