When I was in Holland Jelle Hissink pointed out a quick easy piece of code that is extremely useful in many scenarios I have seen in the past. It maps delegates from Base classes to Derived classes. Previously working with messaging I used the Handles<T> methodology which has since become popular in both MassTransit and nServiceBus. It allowed you to use typed message handlers as opposed to having to write handlers that used the base class then casted to the specific type. This code does the same but using delegates which is pretty slick and can be used in an aggregate root base class quite easily to handle the mapping of events to methods that apply them internally (you can also use it for event/command handlers if you don’t want to use an existing framework such as nServiceBus or MassTransit). Here is the code.
public class DelegateAdjuster
{
public static Action<BaseT> CastArgument<BaseT, DerivedT>(Expression<Action<DerivedT>> source) where DerivedT : BaseT
{
if (typeof(DerivedT) == typeof(BaseT))
{
return (Action<BaseT>)((Delegate)source.Compile());
}
ParameterExpression sourceParameter = Expression.Parameter(typeof(BaseT), "source");
var result = Expression.Lambda<Action<BaseT>>(
Expression.Invoke(
source,
Expression.Convert(sourceParameter, typeof(DerivedT))),
sourceParameter);
return result.Compile();
}
}
Simple, and slick.
Posted
Sat, Oct 3 2009 7:27 AM
by
Greg