2012-08-01 48 views
2

我開始使用棱鏡和MVVM一個WPF項目時,我試圖用eventAggregator但是,當執行線下則會引發異常情況:EventAggregator和服務定位問題

IServiceLocator ob = ServiceLocator.Current; // This line causes a Null pointer exception 
EventAggregator = ob.GetInstance<IEventAggregator>(); 

,但我不能瞭解我做錯了什麼,也許這是一件非常簡單的事情,但我一直在爲此掙扎幾個小時。

希望有人可以幫助我,在此先感謝

+1

此代碼在哪裏執行以及您正在使用哪個引導程序?例如,如果它是Unity,則應該使用'IUnityContainer'來解析實例,而不是'ServiceLocator'。 – 2012-08-01 18:38:59

+0

我沒有使用任何引導程序,但感謝Wiktor Zychla我解決了我的問題 – Dante 2012-08-01 19:11:29

回答

4

您缺少您的定位器的初始化代碼。

要麼你使用棱鏡(你呢?),你需要正確設置你的引導程序 - http://msdn.microsoft.com/en-us/library/gg430868(PandP.40).aspx

,或者您不使用棱鏡和你剛纔設置的定位手動(在Main爲例):

IUnityContainer container = new UnityContainer(); 

// register the singleton of your event aggregator 
container.RegisterType<IEventAggregator, EventAggregator>(new ContainerControlledLifetimeManager()); 

ServiceLocator.SetLocatorProvider(() => container); 

那麼你就可以在你的代碼

var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>(); 

編輯的任何地方撥打:您已經編輯你的問題,你現在提棱鏡。然後您應該創建一個自定義引導程序,註冊您的類型並運行引導程序。

public class CustomBootstrapper : UnityBootstrapper 
{ 
} 

,並在應用程序的啓動程序調用

var bootstrapper = new CustomBootstrapper(); 
bootstrapper.Run(); 

。從我記得,UnityBootstrapper註冊IEventAggregator作爲單身人士,所以你不必重複這一點。

+0

因爲我是使用棱鏡新的,我不知道我必須初始化定位器。非常感謝你!! – Dante 2012-08-01 19:07:20