How I removed magic strings from my fubuMVC redirection policy

In my previous post on my experiences with fubuMVC I had implemented a redirection policy but was not too happy with the magic strings needed within my convention to point at the methods on my home controller.

Here’s what I currently have:

    public class PermanentRedirectionConvention : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof(HomeController)
                            && c.FirstCall().Method.Name.ToLower() == "news")
                .Each(c => c.Prepend(new Wrapper(typeof(PermanentNewsRedirectionBehaviour))));

            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof(HomeController)
                          && c.FirstCall().Method.Name.ToLower() == "about")
                .Each(c => c.Prepend(new Wrapper(typeof(PermanentAboutRedirectionBehaviour))));
        }
    }

Above, I am using the FirstCall() method to retrieve the ActionCall and examining the handler type and method info to establish if it meets my criteria.

To improve this I need an extension method on the ActionCall that will let me point at a method on it’s HandlerType, so this argument will need to be an Expression<Action<THandlerType>> :

    public static class BehaviourExtensions
    {
        public static bool MatchesHandler<THandlerType>(this ActionCall actionCall, 
                                     Expression<Action<THandlerType>> handlerExpression)
        {
            var methodCallExpression = handlerExpression.Body as MethodCallExpression;
            if(methodCallExpression==null)
                throw new Exception("Expected a method call expression");

            return typeof(THandlerType) == actionCall.HandlerType 
                   && methodCallExpression.Method == actionCall.Method;
        }
    }

This new extension method returns the match between the generic THandlerType and the ActionCall’s HandlerType and also the method from the method call expression against the ActionCall’s method.

This now enables me to remove my magic strings:

    public class PermanentRedirectionConvention : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Behaviors
                .Where(c => c.FirstCall()
.MatchesHandler<HomeController>(controller => controller.News())) .Each(c => c.Prepend(new Wrapper(typeof(PermanentNewsRedirectionBehaviour)))); graph.Behaviors .Where(c => c.FirstCall()
.MatchesHandler<HomeController>(controller => controller.About())) .Each(c => c.Prepend(new Wrapper(typeof(PermanentAboutRedirectionBehaviour)))); } }



0 comments: