Friday, October 28, 2016

Pre and Post Action/Function Decorator

In one of the old project, I had to intercept the call for the existing function in order to log and do some stuff therefore, In order to achieve that without modifying the existing function as it was working and was old enough not to touch. Therefore, After going through resources i came across this article which describes the function decorator.

I decided to implement the ActionExtension to implement Pre and Post Interceptor for existing functions.

The ActionExtension function looks like below.

Note: The action interceptor are need to be defined depending on the number of parameters. I had to implement it for action which accepted only two parameters therefore i had two action extension method which accepts two parameters. For different number of parameters you will need to add more action extensions.



 public static class ActionExtension
    {
        public static Action<targ1, targ2> PreProcessor<targ1, targ2>(this Action<targ1, targ2> action, Action<targ1, targ2> preActionToRun, Targ1 tArg1, Targ2 tarArg2)
        {
            return (TRArg1, TRarg2) =>
            {
                /* PreProcessing */
                preActionToRun(tArg1, tarArg2);

                /* Processing */
                action(tArg1, tarArg2);
            };
        }

        public static Action<targ1, targ2> PostProcessor<targ1, targ2>(this Action<targ1, targ2> action, Action<targ1, targ2> postActionToRun, Targ1 tArg1, Targ2 tarArg2)
        {
            return (TRArg1, TRarg2) =>
            {

                /* Processing */
                action(tArg1, tarArg2);

                /* PostProcessing */
                postActionToRun(tArg1, tarArg2);
            };

        }
    }

No comments:

Post a Comment