I have a simple generic error handler IErrorHandler<T> where T is an exception. I'm using structuremap to get the concrete implementation of the handler based on the exception raised in Application_Error. So here is the code I use to get the handler.
var exceptionType = ex.GetType();
var handlerType = typeof(IErrorHandler<>).MakeGenericType(exceptionType);
var handler = IoCContainer.GetInstance(handlerType); // this returns an object
At this point, Structuremap has returned the correct implementation. But handler is an object, so I can't call any functions that the interface has. I can use reflection to find the Handle method, but that's fragile.
var handle = handlerType.GetMethod("Handle");
handle.Invoke(handler, new[] {ex});
Is there a better way to cast an open generic when the type the generic is using is only known at runtime?
Handlemethod itself generic? - bornfromaneggobject. You can only cast to some non-generic base-interface that your generic ones derives from. - HimBromBeere