2009-07-21 51 views
0

我正在使用棱鏡和統一。爲什麼我的注入依賴對象不是每個模塊中的同一個實例?

我有了這個引導程序

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

我不知道如果我給你足夠的答案,如果是請你將其標記爲「答案」? – galaktor 2009-08-21 20:09:46

回答

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>(); 
相關問題