IInitializable - mariaheine/Zenject-But-Wiki GitHub Wiki
If you have some initialization that needs to occur on a given object, you could include this code in the constructor. However, this means that the initialization logic would occur in the middle of the object graph being constructed, so it may not be ideal.
A better alternative is to implement IInitializable
, and then perform initialization logic in an Initialize()
method.
Then, to hook it up in an installer:
Container.Bind<IInitializable>().To<Foo>().AsSingle();
Or if you don't want to have to always remember which interfaces your class implements, you can use the shortcut described here.
The Foo.Initialize
method would then be called after the entire object graph is constructed and all constructors have been called.
Note that the constructors for the initial object graph are called during Unity's Awake event, and that the IInitializable.Initialize
methods are called immediately on Unity's Start event. Using IInitializable
as opposed to a constructor is therefore more in line with Unity's own recommendations, which suggest that the Awake phase be used to set up object references, and the Start phase be used for more involved initialization logic.
This can also be better than using constructors or [Inject]
methods because the initialization order is customizable in a similar way to ITickable
, as explained here.
public class Ship : IInitializable
{
public void Initialize()
{
// Initialize your object here
}
}
IInitializable
works well for start-up initialization, but what about for objects that are created dynamically via factories? (see this section for what I'm referring to here). For these cases you will most likely want to either use an [Inject]
method or an explicit Initialize method that is called after the object is created. For example:
public class Foo
{
[Inject]
IBar _bar;
[Inject]
public void Initialize()
{
...
_bar.DoStuff();
...
}
}