I’ve found a method using reflection (and got it’s MethodInfo). How can I invoke it without getting TargetInvocationException when exceptions are thrown?
Update
I’m creating a command implementation where the commands are handled by classes which implemement
public interface ICommandHandler<T> where T : class, ICommand
{
public void Invoke(T command);
}
Since there is one dispatcher which takes care of find and map all handlers to the correct command I can’t invoke the methods directly but by using reflection. Something like:
var handlerType = tyepof(IHandlerOf<>).MakeGenericType(command.GetType());
var method = handlerType.GetMethod("Invoke", new [] { command.GetType() });
method.Invoke(theHandler, new object[]{command});
It works fine, but I want all exceptions to get passed on to the code that invoked the command.
So that the caller can use:
try
{
_dispatcher.Invoke(new CreateUser("Jonas", "Gauffin"));
}
catch (SomeSpecificException err)
{
//handle it.
}
Instead of having to catch TargetInvocationException.
(I know that I can throw the inner exception, but that’s pretty worthless since the stack trace is destroyed)
Update2
Here is a possible solution..
But it seems more like a hack. Aren’t there a better solution? Maybe with expressions or something?
Create a
Delegatefrom theMethodInfo(through one of the overloads ofDelegate.CreateDelegate) and invoke that instead. This won’t wrap any exception thrown by the method inside aTargetInvocationExceptionlikeMethodInfo.Invokedoes.EDIT:
(As the OP has pointed out, DynamicInvoke won’t work here since it wraps too)
Based on your update, I would just use
dynamic: