13. Interfaces

  03. Features No Comments


Classes that implement one of the generic IArgs<T…> interfaces can receive one or more arguments, up to a maximum of five, during initialization.

Any object that implements an IArgs<T…> interface makes a promise to receive arguments that have been injected for them during their initialization phase, using the InitArgs.TryGet method.

Classes that derive from MonoBehavour or ScriptableObject should usually retrieve their dependencies during the Awake event function. One thing to note though is that the Awake event function does not get called for components on inactive GameObjects, so it is recommended for all MonoBehaviour-derived classes to implement IInitializable<T…> instead for more reliable dependency injection.

Technically it is also possible for MonoBehaviours to receive their dependencies in the constructor. However it is important to understand that the constructor gets called before the deserialization process, which means that the values of any serialized fields into which you assign your dependencies could get overridden during deserialization. If you only create your instances procedurally at runtime or only assign values to non-serialized fields, this can still be a workable solution, but beware that is is easy to make mistakes if you decide to go this route.


Classes that implement IInitializable<T…> have all the same functionality that they would get by implementing an IArgs<T…> interface, but with additional support for their Init function to be called manually by other classes.

This makes it possible for classes to inject dependencies even in cases where the object can’t receive them independently during initialization.

It also makes it possible to initialize objects with dependencies more than once, which might be useful for example when utilizing the Object Pool pattern to reuse your instances.

For MonoBehaviour derived classes it is generally recommended to implement IInitializable<T…> and not just IArgs<T…>. This is because the Awake event function does not get called for MonoBehaviour on inactive GameObjects, which means that dependency injection could fail unless the injector can manually pass the dependencies to it.

Leave a Reply

Your email address will not be published. Required fields are marked *