04. Initializer

  03. Features No Comments

A major benefit of injecting dependencies from the outside through the Init method is that it makes it easy to decouple your components from specific implementations, provided you use interfaces instead of specific classes as your argument types. The list of arguments that the Init method accepts also makes it very clear what other objects the client objects depends on.

On the other hand, the ability to assign values using Unity’s inspector is also a very convenient and powerful way to hook up dependencies; you can completely change object behaviour without having to write a single line of code!

The Initializer system is a solution that aims to marry the best of both worlds!

You can define an Initializer for component TComponent which inherits from MonoBehaviour<TArgument> using the following syntax:

TComponentInitializer : Initializer<TComponent, TArgument> { }

Then if you add both TComponent as well as TComponentInitializer to the same GameObject, you can specify all the arguments that TComponent’s Init method takes using the inspector.

Initializers allow you to assign argument values even for interface types, and regardless of whether or not they derive from UnityEngine.Object or are plain old class objects.

Another cool benefit of the Initializer system is that it automatically detects when argument types are service types, and can automatically retrieve instances to the these at runtime. Thus you can easily mix and match service arguments and arguments that have been manually assigned through the inspector.

Leave a Reply

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