Thursday, January 13, 2011

Troubleshooting “Exception has been thrown by the target of an invocation”

You’ve probably run across this Exception in a number of different situations. In my case, I ran into it most recently while doing some plumbing changes on our application, which is a composite application built using CAB (Composite UI Application Block). One of the most common failures we run into when wiring up new views or controllers is when an Exception occurs within the initialization logic of one or both of these.

CAB utilizes ObjectBuilder2  for dependencies. You will most often get the above exception when construction of your object occurs because ObjectBuilder2 is going through Activator to instantiate the object you asked for.

The problem with this Exception is that it masks the actual problem that is occurring. In my most recent case, it was caused by a null reference that wasn’t being checked. Unit testing and checking for a null reference would have solved this problem prior to doing the wiring (obviously); however, lacking those in the code base I’m working in currently, the best option was to break on the Exception in the debugger and see what was up.

It’s somewhat annoying that the InnerException is null in this case. The stack trace did however yield some insight into the problem and helped to solve the problem.

In my case, starting at the top of the chain with the constructor of the new object helped to ferret out the problem. From there, I was able to go back and properly check my state and handle the null situation without it being a problem.

Hope this helps…

No comments:

Post a Comment