I command you (pattern)

Which one of us doesn’t like to give commands? It’s the natural way to ask (in a polite way) for a specific task that needs to be completed. Therefore, it shouldn’t be surprising that the command pattern can be also easily implemented within our software, which might provide some serious benefits in terms of loose coupling the existing code.


 

This is going to be mostly about the code, so let’s write some code and find out what’s the fuss about:

At first, let’s define three simple interfaces. The first one is merely a marker interface, and the second one is actually responsible for ensuring that the given command goes into the right direction. The last fella is a kind of helper, that dispatches the commands automatically (to the appropriate instance of the ICommandHandler). Let’s stay with him for a while and see how we could implement such functionality e.g. by using the IoC container (Autofac in this example):

Ok, so what’s actually the command entity? Just a class, that may contain some properties:

And the handler for such command:

And what’s the benefit? Well, most importantly the commands encapsulate the business logic. They might also be a part of a bigger flow – events and some other useful stuff that I’ll talk about in the future. Please take a look, how we can make use of the ICommandDispatcher within the MVC application:

Again, a rather simplistic example. You might want to pass the view model first, then map it into the command etc. The key here is to realize the benefit of using the commands and abstracting away all the business logic e.g. from the controllers. The commands also fit nicely within the CQS and CQRS patterns, which are very powerful.

In one of the next posts, I’ll show you how to make your actions inside the Web/API controllers look cool (at least for me) while using the commands. And that’s a little sneak peek:

16 Comments I command you (pattern)

  1. Pingback: I command you (pattern) - How to Code .NET

  2. Pingback: Dew Drop - July 25, 2016 (#2294) - Morning Dew

  3. fsdfs

    You have a typo. Your command class is called CreateUser, but the handler receives Register.

    Reply
  4. Pingback: "Dead or alive, you're linking with me!" - Robocop - Magnus Udbjørg

  5. Krzyrok

    I will touch only last “sneak peak”.
    Method chaining can be nice (readable) solution if every (controller) method has different strategy of command execution (e.g. one adds OnFailure callback, another one does not).
    But if execution pattern is the same for every command, then it is worth to consider e.g. decorator pattern (which can be nicely used with DI container).
    And I prefer (it’s just my opinion) controllers as thin as possible 🙂 So I would move notifying part to the command handler – command handler (or domain entity) can raise an event when action is completed. IMO controller has less responsibilities (it doesn’t have to notify) in this case – all business logic is moved to the separate place. Controller calls only particular command handler and redirects to some site.

    I like the idea of separate place for mapping.

    I will wait for the next post and full code 😉

    Reply
    1. Piotr Gankiewicz

      Good point, controllers should be as thin as possible, yet in that example e.g. the notification is a part of the MVC view, so it has to be delivered somehow and I’d rather keep commands separate from the UI part :).
      Speaking of domain events and other useful patterns I use them on a daily basis and find to be really helpful. Not sure when I post the full code yet, as it still needs some refactoring, but definitely at some point in the future.
      Please take a look at this post http://lmarcinek.pl/asp-net-mvc-method-chaining-w-kontrolerach/ – seems that other guys also find this chaining to be a nice solution ;).

      Reply
  6. Pingback: Handling domain events | Piotr Gankiewicz

  7. Pingback: .NET Core + RabbitMQ = RawRabbit | Piotr Gankiewicz

  8. Pingback: Async HTTP API and service bus | Piotr Gankiewicz

  9. Pingback: Becoming a software developer – episode VIII | Piotr Gankiewicz

  10. Dan

    If you instead just store one command per controller, you don’t need the dispatcher. Just IoC inject the command handler interface and you are good to go. Otherwise, you are using Service Locator which is an anti-pattern to lookup all these command handlers. We have no idea what the true dependency the controller has.

    Reply
    1. Piotr Gankiewicz

      That’s also a viable solution, however, I will not agree that the presented solution looks like a Service Locator. You know what your dependencies are thanks to the commands that are being passed through the endpoints that you can easily test.

      Reply
      1. Dan

        As soon as you reference your container outside of the root, you are doing Service Locator. It may seem innocent here and your Query/Command is technically 1:1, but if someone created this without DI, they’d new up a Dispatcher and send it in without realizing that they also have to add the right interfaces/classes to the IoC container or it won’t work.

        Reply
    1. Piotr Gankiewicz

      Sure, you just need to register the dispatchers e.g.

      builder.RegisterType().As().SingleInstance();

      And then the handlers:

      var assembly = typeof(Startup).GetAssembly();
      builder.RegisterAssemblyTypes(assembly).AsClosedTypesOf(typeof(ICommandHandler<>));

      Reply

Leave A Comment

Your email address will not be published. Required fields are marked *