More on Logging UnhandledExeptions from Managed Add-Ins [Jesse Kaplan]
Last time we discussed some issues to be aware of when trying to build hosts that are resilient to failures in their add-ins.
The central idea was to subscribe to the UnhandledException event on the hosts AppDomain and to use the "sender" parameter to associate the exception to the add-in that caused it. The main limitation of the approach discussed for detecting and logging unhandled exceptions from the add-in's was that it only worked when the host itself was running in the default AppDomain and that this excluded hosts that themselves run inside other hosts (such as IIS).
This time we are taking a slightly different approach that works regardless of which AppDomain the host is running in, but has a different limitation. Instead of subscribing to the event on the host's domain, you can subscribe to them individually on each add-ins AppDomain. This causes a subtle but important difference in the way the handling code for that domain runs: it always executes in the domain that fires the event regardless of where the subscriber came from. This means that the piece of code handling this event needs to be loaded in the add-ins domain and, for versioning reasons, should be as small and have as few dependencies as possible. By keeping this code small and with few dependencies you reduce the chances that the code conflicts with the add-ins dependencies and causes a failure. In the attached sample I have refactored the code for handling exceptions into a separate assembly and made sure it was independent from the host and so brought no other pieces of the host into the add-ins AppDomain. There were a few small tweaks to the host itself, but all the interesting changes take place in the new UnhandledException project.
So the pattern used in the sample can work with hosts in non-default domains at the expense of having a slightly higher risk of causing versioning problems butwith careful coding you can minimize this risk.
Note: The attached sample was built for a pre-RTM version of .NetFX 3.5 and will not work on the RTM build. For an updated sample please see our codeplex site here: https://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=clraddins&ReleaseId=9456