Skip to main content

Implementing Chain of Responsibility Design Pattern in C# using Managed Extensibility Framework (MEF)

imageThis post is about implementing Chain Of Responsibility design pattern, and few possible extensions to the same. If you are new to design patterns, I suggest you should start with Practically Applying Design Patterns  – Thought Process

Coming back to Chain of Responsibility - If you have a scenario where you need to chain multiple handlers to handle an incoming request or command, you better use Chain Of Responsibility.

A typical example is your girlfriend requesting you something –  If she is requesting/commanding you something like “Do you want to come with me for my best friend’s Bachelorette party?”, you will handle it directly. But if she is requesting/commanding you some thing like “Buy me a Porsche”, you say “Sorry Honey, I don’t have the money. Better you ask your dad for this, I’ll call him for you” –i.e, you pass the request to the next handler, in this case your girl friend’s Father. To sum up, in the above example, your girl friend is the client who is making the request, and you and your future father-in-law are handlers/approvers who handle/approve her requests. If you cannot handle it, you pass that responsibility to the next handler/approver in the chain.

A Minimal Example

To consider a more formal example, assume a scenario where you’ve a banking system, and you want to implement some kind of Loan approval. The customer may request a loan, and if it is below a specific amount, the cashier may  approve it directly. If it is above the specified amount, he might pass the request to his manager for approval.

So you may use Chain Of Responsibility implementation to hand over the request/command to the correct approver. For an example, consider this implementation of the above Bank account scenario. Our business rule is something like, a cashier can approve the request if the amount is lesser than 1000 $$, other wise the approval should be passed to the manager. The manager can approve the request if the amount is lesser than 10,000 $$.

We have the following components.

  • LoanRequest – A concrete request
  • IRequestHandler – Abstract request handler implementation
    • Concrete handlers like Cashier and Manager implements this
    • Has a reference to the successor to pass the request
  • Program – The main driver

 

To the code

using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatternsCof
{

 
    //Request
    class LoanRequest
    {
        public string Customer { get; set; }
        public decimal Amount { get; set; }
    }

    //Abstract Request Handler
    interface IRequestHandler
    {
        string Name { get; set; }
        void HandleRequest(LoanRequest req);
        IRequestHandler Successor { get; set; }
    }

    //Just an extension method for the passing the request
    static class RequestHandlerExtension
    {
        public static void TrySuccessor(this IRequestHandler current, LoanRequest req)
        {

            if (current.Successor != null) 
            {
                Console.WriteLine("{0} Can't approve - Passing request to {1}", current.Name, current.Successor.Name);
                current.Successor.HandleRequest(req);
            }
            else
            {
                Console.WriteLine("Amount invaid, no approval given");                
            }
        }
    }

    //Concrete Request Handler - Cachier
    //Cachier can approve requests upto 1000$$
    class Cashier : IRequestHandler
    {
        public string Name { get; set; }
        
        public void HandleRequest(LoanRequest req)
        {
            Console.WriteLine("\n----\n{0} $$ Loan Requested by {1}",
                  req.Amount, req.Customer);

           if (req.Amount<1000)
               Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                    req.Amount,req.Customer, this.Name);
           else
               this.TrySuccessor(req);
        }

        public IRequestHandler Successor { get; set; }       
    }

    //Concrete Request Handler - Manager
    //Manager can approve requests upto 10000$
    class Manager : IRequestHandler
    {
        public string Name { get; set; }
        public void HandleRequest(LoanRequest req)
        {
            if (req.Amount < 10000)
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                         req.Amount, req.Customer, this.Name);
            else
               this.TrySuccessor(req);

        }
        public IRequestHandler Successor { get; set; }  
    }

   

    //Main driver
    class Program
    {
        static void Main(string[] args)
        {
            //Customers
            var request1 = new LoanRequest() { Amount = 800, Customer = "Jimmy"};
            var request2 = new LoanRequest() { Amount = 5000, Customer = "Ben"};
            var request3 = new LoanRequest() {Amount = 200000, Customer = "Harry"};

            //Approvers, chained together
            var manager = new Manager() {Name = "Tom, Manager"};
            var cashier = new Cashier(){ Name = "Job, Cachier", Successor = manager};

            //All customers request cashier first to approve
            cashier.HandleRequest(request1);
            cashier.HandleRequest(request2);
            cashier.HandleRequest(request3);

            Console.ReadLine();
        }


    }
}

And this is what you’ll see upon execution.

image

So, you may observe that Loan Requests from different customers are passed to the cashier in the above example, and the cashier in his approve method passes the request to his successor (i.e, the manager) if the amount is higher than what he can approve. The implementation is pretty minimal, as you can see.

image

We actually  have an Abstract request handler implementation IReqeustHandler and two concrete request handlers, Cashier and Manager. Each request handler may hold a reference to the successor. You may see that we are setting the Successor of Cashier as Manager, so if the  amount requested his beyond a limit, the cashier may pass it to the manager for his approval.

Dynamically Injecting Approvers

Now, let us take a step back, and think how to implement this in such a way that the approval pipeline is extensible? As of now, our pipeline has two approvers, cashier and manager, and the manager can approve loans up to 10,000. Tomorrow, the Bank may decide that the General Manager can approve loans above 10,000 – and what you are going to do? Make the changes, Recompile the entire application, move it to QA, initiate a full recursion testing, and deploying everything to production? You may leverage a bit of extensibility here, and let us have a look at leveraging MEF (Managed Extensibility Framework) for the same.

I recommend you to go through my introductory posts on MEF if you are not familiar with MEF concepts.

Let us go for a generic implementation, to load and compose the handlers leveraging MEF. Let us generalize the above implementation a bit, and introduce few more general purpose contracts and classes.

  • IRequest – This contract should be implemented by all requests.
  • IRequestHandler – Same as earlier. Abstract request handler implementation
  • ExportHandlerAttribute – A custom attribute to export MEF parts
  • IRequestHandlerMetadata – Used internally for storing the successor information as a type
  • RequestHandlerGateway – Does the composition, and passes the request to successors in a chained fashion.

To the code

    //Abstract Request 
    public interface IRequest { }


    //Abstract Request Handler
    public interface IRequestHandler
    {
        bool HandleRequest(IRequest req);
        IRequestHandler Successor { get; set; }
    }

    //A custom MEF Export attribute
    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]  
    public class ExportHandlerAttribute : ExportAttribute 
    {
        public Type SuccessorOf { get; set; }

        public ExportHandlerAttribute()
            : base(typeof(IRequestHandler))
        {
        }

        public ExportHandlerAttribute(Type successorOf)
            : base(typeof(IRequestHandler))
        {
            this.SuccessorOf = successorOf;
        }
    }

    //The metadata to tie a handler to next successor
    public interface IRequestHandlerMetadata
    {
        Type SuccessorOf { get; }
    }

    //A gateway which stiches together the handlers, to accept a request to chain through the handlers
    //Note that this does the composition using MEF
    public class RequestHandlerGateway
    {
        [ImportMany(typeof(IRequestHandler))]
        public IEnumerable<Lazy<IRequestHandler,IRequestHandlerMetadata>> Handlers { get; set; }

        private IRequestHandler first = null;

        public RequestHandlerGateway()
        {
            ComposeHandlers();

            //Let us find and keep the first handler
            //i.e, the handler which is not a sucessor of any other handlers            
            first = Handlers.First
                    (handler => handler.Metadata.SuccessorOf == null).Value;
        }

        //Compose the handlers
        void ComposeHandlers()
        {
            //A catalog that can aggregate other catalogs
            var aggrCatalog = new AggregateCatalog();
            //An assembly catalog to load information about part from this assembly
            var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            aggrCatalog.Catalogs.Add(asmCatalog);

            //Create a container
            var container = new CompositionContainer(aggrCatalog);
            //Composing the parts
            container.ComposeParts(this);
        }

        //Try to handle the request, pass to successor if required
        bool TryHandle(IRequestHandler handler, IRequest req)
        {
            var s =
                Handlers.FirstOrDefault(
                    h => h.Metadata.SuccessorOf == handler.GetType());

            if (handler.HandleRequest(req)) 
                return true;
            else if (s != null)
            {
                handler.Successor = s.Value;
                return TryHandle(handler.Successor, req);
            }
            else
                return false;
        }

        //Main gateway method for invoking the same from the driver
        public bool HandleRequest(IRequest request)
        {
            return TryHandle(first,request);
        }
    }    

Cool. So we have the basic stuff there, keep that handy. Now, to have a Chain Of responsibility implementation, you can simply create the concrete parts and export the same. We’ve the following concrete parts.

  • LoanRequest – A concrete request
  • Cashier, Manager, and GeneralManager – Concrete request handlers

You may note that now we can chain the handlers using the Meta data. For example, when you export the manager, you can easily specify that Manager is the successor of Cashier, to approve the request. Similarly, you can specify General Manager as the successor of the Manager. The advantage is, you can simply deploy these components in a loosely coupled manager, and pick them up using the DirectoryCatalog of MEF during re composition.

    //Concrete Request
    public class LoanRequest : IRequest
    {
        public string Customer { get; set; }
        public decimal Amount { get; set; }
    }


    //Concrete Request Handler - Cachier
    //Cachier can approve requests upto 1000$$
    [ExportHandler]
    public class Cashier : IRequestHandler
    {
      
        public bool HandleRequest(IRequest r)
        {
            var req = (LoanRequest)r;
            if (req.Amount < 1000)
            {
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                                  req.Amount, req.Customer, this.GetType().Name);
                return true;
            }

            return false;

        }

        public IRequestHandler Successor { get; set; }
    }

    //Concrete Request Handler - Manager
    //Manager can approve requests upto 10000$
    [ExportHandler(SuccessorOf = typeof(Cashier))]
    public class Manager : IRequestHandler
    {
     
        public bool HandleRequest(IRequest r)
        {
            var req = (LoanRequest)r;
            if (req.Amount < 10000)
            {
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                                  req.Amount, req.Customer, this.GetType().Name);
                return true;
            }

            return false;
        }

        public IRequestHandler Successor { get; set; }
    }


    //Concrete Request Handler - Manager
    //Manager can approve requests upto 10000$
    [ExportHandler(SuccessorOf = typeof(Manager))]
    public class GeneralManager : IRequestHandler
    {

        public bool HandleRequest(IRequest r)
        {
            var req = (LoanRequest)r;
            if (req.Amount < 100000)
            {
                Console.WriteLine("{0} $$ Loan approved for {1} - Approved by {2}",
                                  req.Amount, req.Customer, this.GetType().Name);
                return true;
            }

            return false;
        }

        public IRequestHandler Successor { get; set; }
    }


    //Main driver
    class Program
    {
        static void Main(string[] args)
        {
            //Customers
            Console.WriteLine("Enter Loan Amount:");
            var amount = decimal.Parse(Console.ReadLine());

            var req = new LoanRequest() {Amount = amount, Customer = "Ben"};
            var gateway = new RequestHandlerGateway();
            if (!gateway.HandleRequest(req))
                Console.WriteLine("Oops, too high. Rejected");
            Console.ReadLine();
        }


    }

And this is what you’ll get. You can see that the request gets dispatched to the correct handler.

image

 

image

 

image

 

image

There we go, happy coding with proper decoupling.

Popular posts from this blog

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…

5 Awesome Learning Resources For Programmers (To help you and your kids to grow the geek neurons)

Happy New Year, this is my first post in 2012. I’ll be sharing few awesome learning resources I’ve bookmarked, and will be pointing out some specific computer/programming related courses I've found interesting from these resources.Also, thought about saving this blog post for my kids as well - instead of investing in these Child education schemes (though they are too small as of today, 2 years and 60 days respectively ). Anyway, personally my new year resolution is to see as much videos from this course collections (assuming I can find some free time in between my regular job && changing my babies diapers).1 – Khan AcademyAs I mentioned some time back, you and your kids are missing some thing huge if you havn’t heard about Khan Academy.  It is an awesome learning resource, especially if you want to re-visit your basics in Math, Science etc.With a library of over 2,600 videos covering everything from arithmetic to physics, finance, and history and 268 practice exercises, th…

Hack Raspberry Pi – How To Build Apps In C#, WinForms and ASP.NET Using Mono In Pi

Recently I was doing a bit of R&D related to finding a viable, low cost platform for client nodes. Obviously, I came across Raspberry Pi, and found the same extremely interesting. Now, the missing piece of the puzzle was how to get going using C# and .NET in the Pi. C# is a great language, and there are a lot of C# developers out there in the wild who are interested in the Pi.In this article, I’ll just document my findings so far, and will explain how develop using C# leveraging Mono in a Raspberry Pi. Also, we’ll see how to write few minimal Windows Forms & ASP.NET applications in the Pie as well.Step 1: What is Raspberry Pi?Raspberry Pi is an ARM/Linux box for just ~ $30. It was introduced with a vision to teach basic computer science in schools. How ever, it got a lot of attention from hackers all around the world, as it is an awesome low cost platform to hack and experiment cool ideas as Pi is almost a full fledged computer.  More About R-Pi From Wikipedia.The Raspberry Pi