When using ByInstaller or ByMethod to create subcontainers, lifecycle interfaces like IInitializable, ITickable, and IDisposable are not automatically forwarded to the subcontainer by default. To ensure these events are triggered, you have two primary options:
- Derive the Facade from
Kernel: Make your facade class inherit from Kernel and use BindInterfacesAndSelfTo<T>() in the parent container. This allows the parent container to forward lifecycle calls to the subcontainer. - Use
.WithKernel(): Add the .WithKernel() method to your binding statement. This automatically handles the forwarding of lifecycle events without requiring your facade class to inherit from Kernel.
Note that for dynamically created subcontainers (e.g., via a BindFactory), you must explicitly call the lifecycle methods (like _greeter.Initialize()) on the created instance if you are not using a Kernel-based approach.
// Option 1: Using WithKernel() to enable lifecycle events
public class Greeter
{
public Greeter()
{
Debug.Log("Created Greeter");
}
}
public class TestInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind<Greeter>()
.FromSubContainerResolve()
.ByMethod(InstallGreeter)
.WithKernel() // This enables IInitializable, ITickable, and IDisposable
.AsSingle();
}
void InstallGreeter(DiContainer subContainer)
{
subContainer.Bind<Greeter>().AsSingle();
subContainer.BindInterfacesTo<GoodbyeHandler>().AsSingle();
subContainer.BindInterfacesTo<HelloHandler>().AsSingle();
}
}