Skip to main content

Dependency Injection

DI Container

This holds all the instances needed for injections. There is no need to explicitly create an instance of this as GlacierInjector static class handles it for you.

This container can either hold a singleton instance or a factory. A tag can be set to either of the two.

container.Register<IBall>(() => new Ball(), "theBall");
container.RegisterSingleton<IAudioSystem>(new AudioSystem());

Unless you need to handle an instance of GlacierDIContainer, you can directly use GlacierInjector like so:

GlacierInjector.Register<IBall>(() => new Ball(), "theBall");
GlacierInjector.RegisterSingleton<IAudioSystem>(new AudioSystem());

Injection

You can either resolve a single variable or Inject to all injectable fields. For resolving a single variable:

var ball = GlacierInjector.Resolve<IBall>("theBall");
var ball = GlacierInjector.Resolve(typeof(IBall), "theBall");

If you have member variables that uses the GlacierInject(tag) attribute, you can inject values to the entire class like so:

// Game.cs
public class Game {
    [GlacierInject("theBall")]
    private IBall _ball;

    public Game() {
        GlacierInjector.Inject(this); // Beyond this line, _ball has a value.
    }
}

For Unity GameObjects - if it has one or more MonoBehaviours attached to it with varialbes that use GlacierInject(tag) attribute, you can use GlacierUnityInjector instead:

// Assuming this GameObject has MonoBehaviour scripts attached to it.
var go = GetGameObject();

// Beyond this line, all member variables that use GlacierInject attribute will have values on them.
GlacierUnityInjector.InjectGameObject(go);