我正在開發一個Silverlight 3應用程序,我想委託所有意想不到的錯誤處理在一個名爲ErrorHandler
的類的單個實例中。該類有一個名爲HandleApplicationException
的方法,以及一些處理更多專用錯誤的其他方法。AppDomain.GetData方法不可訪問?
在我的應用程序中,我使用Unity進行依賴注入,但因爲我希望即使Unity容器尚未設置,錯誤處理對象仍然可用,所以我在App類構造函數中將該對象註冊爲AppDomain全局數據,這樣說:
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());
InitializeComponent();
}
而在未處理的異常的情況下,我檢索錯誤處理程序對象,並使用這種方式:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
e.Handled = true;
var errorHandler = AppDomain.CurrentDomain.GetData("ErrorHandler") as ErrorHandler;
Debug.Assert(errorHandler != null, "No ErrorHandler registered.");
errorHandler.HandleApplicationException(e.ExceptionObject);
}
的問題是,AppDomain.GetData
方法在Application_UnhandledException
方法拋出一個MethodAccessException。我不明白爲什麼,因爲我只是在AppDomain類上調用公共方法。我在其他應用程序中使用了類似的方法,它工作正常(反正這些不是Silverlight應用程序)。
那麼,這是怎麼回事?難道我做錯了什麼?
正如我在問題中解釋的,我實際上是在應用程序中使用Unity;但這是一種特殊情況,因爲即使Unity容器尚未創建,我也希望該對象可用。 – Konamiman 2009-11-09 16:15:43