The Scenario:
I have a service that instantiates an object using Activator.GetObject
whose type cannot be known until runtime. All we know ahead of time is that it implements the appropriate interface. (Assembly and Type identification information comes from other received data.) The new object connects to some external device (serial port, TCP socket, whatever) and handles communication with it.
The Problem:
If an exception goes unhandled in one of the threads of that object, where and how can I catch it in my service?
I have tried a handler for AppDomain.CurrentDomain.UnhandledException
in the service object, the object that performs the instantiation, and in the object itself, but none of these will catch the NullReferenceException
that I injected for my testing. (I had it thrown upon retrieving one of the object's properties that the instantiating object accesses from a timer event.) What other options are there?
Further discoveries: The UnhandledException
subscription works for exceptions that happen before the call to ServiceBase.Run()
if the scbscription is placed in Main()
or the ServiceBase
object constructor. But those two (usually trivial) methods are the only things that happen in that space. Once the service is being Started, no subscription works anywhere regardless of where the exception is thrown--even in the very next statement after the subscription.