I am developing a menu service for my application using Prism 7 and Unity 5. The app is WPF, MVVM, modular.
The main menu is a module that is assigned to a region. The menuService keeps track of what menu selections are available and implements the menu object. The menu module registers the menuService as a singleton:
public void RegisterTypes(IContainerRegistry containerRegistry) {
containerRegistry.RegisterSingleton<IMenuService, MainMenuService>();
}
In OnInitialized it resolves the menuService and registers the permanent menu selections.
IMenuService menu = containerProvider.Resolve<MainMenuService>();
menu.AddTopLevelMenu(fileMenu);
menu.AddTopLevelMenu(toolMenu);
menu.AddTopLevelMenu(helpMenu);
When other modules are instantiated I'm using DI to pass in the menuService instance so they can add any additional menu selections. Everything is working, except that the menuService instance being passed to the other modules is a new one, not the one that was initialized in the MenuModule. I have tried using constructor injection and an injection method. They both produce the same result.
I have verified that modules are being instantiated in the proper order. I have browsed the container registry and the menuService is registered with ContainerControlledLifetimeManager.
I can't figure out what I'm missing. Any advice appreciated.
containerRegistry.RegisterSingleton<IMenuService, MainMenuService>();
registers MainMenuService
as singleton implementation of IMenuService
.
containerProvider.Resolve<MainMenuService>();
resolves an instance of MainMenuService
. Which is different from the implementation registered for IMenuService, and in fact not registered at all, and of course also not registered as a singleton. Even if you registered MainMenuService
as a singleton, it would be a different singleton from the singleton registered to implement IMenuService
.
Long story short - resolve IMenuService
and you're fine:
containerProvider.Resolve<IMenuService>();