VContainer
VContainer copied to clipboard
What is the correct way for doing runtime resolve?
This is a basic question. On your site you state this:
var serviceA = container.Resolve<ServiceA>();
"requires more code and obscures your intent."
If this is the case, what is the correct way of getting a new class in runtime? Do you have or know of any game project examples?
For example, I have an interface that exposes a method that is called once the application is loaded. When this happens, I want to create an instance (the single instance since it is a singleton) of the main hub view. Currently what I do is just a single call to the resolve method directly:
public void OnApplicationLoaded()
{
var view = _container.Resolve<MainHubView>();
view.gameObject.SetActive(true);
foreach (var mainHubComponentInstaller in _installers)
{
mainHubComponentInstaller.Install();
}
}
I'm not sure if this is the correct approach since the usage of the resolver is discouraged. Still, a factory here doesn't make sense since this object has standard initialization and is only created once. Is using the object resolver here the correct approach?
From my research, this seems to be the best DI library for unity, but the documentation lacks some real game use-cases. It would be nice to list here any open source games that are using this container.
Thanks!
In general, resolving all dynamically generated objects with DI is very complex. I think we should only DI objects that are statically resolved at the start of scope.
a factory here doesn't make sense since this object has standard initialization and is only created once.
You can DI an object that "manages objects that are dynamically created only once and then cached".
If there is no DI, you are probably creating that class. We do not believe that it is the DI's responsibility to manage very closely the life cycle of individual objects by condition within a game/application.
Also, if many objects with the same dynamic lifetime are generated (like stages in a game), a child LifetimeScope can be generated