IDisposable - mariaheine/Zenject-But-Wiki GitHub Wiki
If you have external resources that you want to clean up when the app closes, the scene changes, or for whatever reason the context object is destroyed, you can declare your class as IDisposable
like below:
public class Logger : IInitializable, IDisposable
{
FileStream _outStream;
public void Initialize()
{
_outStream = File.Open("log.txt", FileMode.Open);
}
public void Log(string msg)
{
_outStream.WriteLine(msg);
}
public void Dispose()
{
_outStream.Close();
}
}
Then in your installer you can include:
Container.Bind(typeof(Logger), typeof(IInitializable), typeof(IDisposable)).To<Logger>().AsSingle();
Or you can use the BindInterfaces shortcut:
Container.BindInterfacesAndSelfTo<Logger>().AsSingle();
This works because when the scene changes or your unity application is closed, the unity event OnDestroy()
is called on all MonoBehaviours, including the SceneContext class, which then triggers Dispose()
on all objects that are bound to IDisposable
.
You can also implement the ILateDisposable
interface which works similar to ILateTickable
in that it will be called after all IDisposable
objects have been triggered. However, for most cases you're probably better off setting an explicit execution order instead if the order is an issue.