Skip to content
skradel edited this page Sep 13, 2010 · 7 revisions

Zetetic.Chain is a .NET / C# library implementing the “chain of responsibility” pattern, very much like Apache Commons Chain. Zetetic.Chain is released under a BSD-style license.

Zetetic.Chain makes it easy to build flexible, loosely-coupled systems, where you can simply run commands by name rather than by embedding a lot of logic and dependencies in your code. Later, you can change and review the behavior of these commands via configuration. This results in cleaner, testable, maintainable code in your application.

For example, if you’re building an application to do something complicated, like ordering the ingredients online to make lemonade, you might not yet know all the steps required to make that happen in real life. And, your ingredient list or online store may change someday, and you might switch payment methods, so you don’t want to build these dependencies in unnecessarily. Using Zetetic.Chain, your code might look like this:

context["GlassesOfLemonade"] = 10;
context["CustomerId"] = "Me";
catalog["OrderLemonadeIngredients"].Execute(context);

All we’ve done here is store some contextual information – how many glasses worth of ingredients we need to order, and for whom – and passed it on to the “OrderLemonadeIngredients” command.

Zetetic.Chain locates the command by name and manages the execution of everything involved in the process. The registry for these commands is the Catalog. Zetetic.Chain includes facilities to read and write the Catalog in XML, and automatically ensures that the commands you include are configured before use.

Sticking with our lemonade example, the Catalog to support ordering ingredients might look like this:

<catalog>
  <chain name="OrderLemonadeIngredients">
    <command name="VerifyQuantity" .... />
    <command name="GetNumberOfLemons" .... />
    <command name="GetTablespoonsOfSugar" .... />
    <command name="GetShippingAddress" .... />
    <command name="GetPaymentInfo" .... />
    <command name="SubmitVendorOrder" .... />
    <command name="RecordReceiptDetails" .... />
  </chain>
</catalog>

In this case, the command named “OrderLemonadeIngredients” is actually a Chain – a series of steps – but the part of your application that just wants to “get it done” doesn’t need to know that.

You can add, modify, and remove steps – like validation to make sure we don’t try to order more than 50 glasses’ worth of ingredients at once – without changing the bulk of your code. Just add another simple command to take a look at the context, and throw an exception if you don’t like what you see. Zetetic.Chain will stop executing the order, and will give each of the commands that already fired an opportunity to handle the exception.

Clone this wiki locally