views:

130

answers:

2

I am developing a Silverlight 3 application and I would like to delegate all unexpected error handling in a single instance of a class I have named ErrorHandler. This class has one method named HandleApplicationException, plus a couple of other methods to handle more specialized errors.

In my application I am using Unity for dependency injection, but since I want the error handling object to be available even when the Unity container is not yet set up, I register the object as AppDomain global data in the App class constructor, this way:

public App()
{
    this.Startup += this.Application_Startup;
    this.Exit += this.Application_Exit;
    this.UnhandledException += this.Application_UnhandledException;

    AppDomain.CurrentDomain.SetData("ErrorHandler", new ErrorHandler());

    InitializeComponent();
}

And in case of unhandled exception, I retrieve the error handler object and use it this way:

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);
}

The problem is that the AppDomain.GetData method in the Application_UnhandledException method is throwing a MethodAccessException. I don't understand why, as I am just invoking a public method on the AppDomain class. I have used a similar approach in other applications and it worked fine (anyway these were not Silverlight applications).

So, what's going on? Am I doing something wrong?

+1  A: 

Ok, I got it. From MSDN documentation:

This member has a SecurityCriticalAttribute attribute, which restricts it to internal use by the .NET Framework for Silverlight class library. Application code that uses this member throws a MethodAccessException.

I have resorted to storing the error handler in a public property in the App class, then I access it using ((App)Application.Current).ErrorHandler. I don't like doing things this way but I suppose it is ok in this special case.

Konamiman
A: 

Why can't you just use a static instance of ErrorHandler? I.e. have something like ErrorHandler.Current?

It looks like you're trying to manually construct a poor man's IoC framework to be honest. Consider doing some research on Unity/Ninject and see for yourself why strongly-typed decoupling is better.

JustinAngel
As I explain in the question, I am actually using Unity in the application; but this is a special case, as I want the object to be available even when the Unity container has not been created yet.
Konamiman