为什么我注入的依赖项对象在每个模块中都不是同一个实例?

Edw*_*uay 0 wpf dependency-injection prism

我正在使用Prism和Unity.

我有这个引导程序:

protected override IModuleCatalog GetModuleCatalog()
{
    ModuleCatalog catalog = new ModuleCatalog()
        .AddModule(typeof(CustomerModule.CustomerModule))
        .AddModule(typeof(EmployeesModule.EmployeesModule))
        .AddModule(typeof(MenuModule.MenuModule));
    return catalog;
}
Run Code Online (Sandbox Code Playgroud)

我的CustomerModule会注入一个MenuManager并向其添加菜单项:

public void Initialize()
{
    menuManager.MenuItems.Add("Customers");
    menuManager.MenuItems.Add("Other Customers");
}
Run Code Online (Sandbox Code Playgroud)

但是当我的MainMenuPresenter对象也被注入MenuManager时,它不是同一个对象:

public MainMenuPresenter(MainMenuView view, MenuManager menuManager)
{
    View = view;
    View.DataContext = this;

    foreach (string menuItemTitle in menuManager.MenuItems)
    {
        MenuItems.Add(menuItemTitle);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何告诉Prism/Unity我希望注入的MenuManager是Singleton,以便将相同的对象注入到我的每个模块和对象中?

gal*_*tor 6

使用Unity,你可以这样做(取自Unity上Lifetime Manager的MSDN):

// 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>();
Run Code Online (Sandbox Code Playgroud)