我正在使用Prism和Unity。
我有 bootstrapper :
protected override IModuleCatalog GetModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog()
.AddModule(typeof(CustomerModule.CustomerModule))
.AddModule(typeof(EmployeesModule.EmployeesModule))
.AddModule(typeof(MenuModule.MenuModule));
return catalog;
}
我的 CustomerModule 会注入一个MenuManager并向其中添加菜单项:
public void Initialize()
{
menuManager.MenuItems.Add("Customers");
menuManager.MenuItems.Add("Other Customers");
}
但是当我的 MainMenuPresenter 对象也注入了MenuManager时,它不是同一个对象:
public MainMenuPresenter(MainMenuView view, MenuManager menuManager)
{
View = view;
View.DataContext = this;
foreach (string menuItemTitle in menuManager.MenuItems)
{
MenuItems.Add(menuItemTitle);
}
}
如何告诉Prism / Unity我希望注入的MenuManager是Singleton,以便将相同的对象注入到我的每个模块和对象中?
答案 0 :(得分:6)
使用Unity,你可以这样做(取自MSDN on Lifetime Managers in Unity):
// Register a type to have a singleton lifetime without mapping the type
// Uses the container only to implement singleton behavior
myContainer.RegisterType<MySingletonObject>(new ContainerControlledLifetimeManager());
// Following code will return a singleton instance of MySingletonObject
// Container will take over lifetime management of the object
myContainer.Resolve<MySingletonObject>();