Good morning,
Context
I have this factory
public class ViewFactory : IViewFactory
{
private readonly DiContainer _container;
[Inject]
public ViewFactory(DiContainer container)
{
_container = container;
}
public GameObject CreateView(ViewData viewData, Transform parent)
{
return _container.InstantiatePrefab(viewData.ViewPrefab, parent);
}
}
installed in the ProjectContext as it’s a dependency of my ViewService class that is also installed there.
Injected container in that factory is of course global container which make my factory always create my views in the ProjectContext.
Problem
My problem is, that my View created by this factory have a dependency of a ViewModel class that is installed in the scene context, which makes it impossible for zenject to inject it.
I understand that it’s not possible as view and its view model lives in a different containers (and it’s a parent container class that requires sub-container dependency, I’m aware that if it was the other way around the problem will probably not occur)
Here is how I install my bidnings in ProjectContext:
Container.BindInterfacesAndSelfTo<ViewFactory>().AsSingle();
Container.BindInterfacesAndSelfTo<ViewsService>().AsSingle();
I install my ViewModels in a same manner but just on the SceneContext installer, nothing fancy here.
So I’m just wondering
-
Can I somehow solve that problem with different way of installing my stuff or some other Zenject Magic tricks i’m not aware of?
-
Is possible to have a factory installed in the ProjectContext that will spawn objects in the current context instead of a ProjectContext?*
*Of course I could do some kind of provider of context to that factory, make sure it’s provided before it creates the object but since i’m trying to learn more about Zenject here, i’m just curious about other perspectives to this problem
Some constraints
I’m open to all ideas, however, there are some things that can’t be changed and I would appreciate if you take them into your considerations before answering
-
Zenject stays (I won’t change it to other DI solution)
-
ViewService have to be installed in ProjectContext
-
ViewService have to be responsible for delegating the “Create view” task (can delegate that to factory, can spawn it itself, but that creation has to go through this service)
-
ViewModel has to stay as a dependency of a View not the other way around
-
ViewModel installation can’t be moved to ProjectContext (unless there is a way that it’ll still be only visible in a scene context)
Thank you very much for your time!