How to use partial application like DI?

I had an interesting question today on twitter from someone having some issues trying to do what I discuss in my 8 lines of code talk

Unfortunately though while the Event Store does manual wire up it does not also use partial application in that code so its not a great example so I asked for a gist with example code to see what the problem may be.

https://gist.github.com/ndonze/7675989

As you can see the types are the big problem here as it wants a List<Func<IMessage, IHandlerResult>>() unfortunately the compiler will not like this (some languages can actually do this! C# is not one of them). I replied with the following code that works for the particular case

This code is very similar to the first bit (still registers up handlers etc) but it has one small trick being played in it. In particular when registering a handler you will notice:

_dictionary.Add(typeof(T), x => func((T)x));

Internally the Dictionary stores as an internal interface for IMessage. This line of code causes the cast to happen. If I were to write it out as a full function it would look something like:

static MyReturn Convert(IMessage message) {

OtherHandler((ConcreteMessage) message)

}

This allows all the internal things to be treated and dispatched as IMessage but the outside handlers to use a ConcreteMessage. We can go one step further than this though (and probably should). Note that the code is no less testable, we are just passing in dependencies in a different way.

Why should I TELL you what IMessage must be?

This same code can also work for command handlers as well as queries. In order to do this we will take direction from F# (as well as many other languages) and introduce a type that represents void. We need to do this as System.Void is not allowed to be used for generic arguments.

https://gist.github.com/gregoryyoung/7677751

Now we can use this in conjunction with our dispatcher to handle commands as well as an Action<TCommand> is equivalent to a Func<TCommand, Nothing>

Now we can use the same code in either place!

13 Comments

  1. Posted November 27, 2013 at 8:17 pm | Permalink | Reply

    Nothing is the good trick, but C# is not an F#. With that design, you’re forcing to have a mandatory return statement in every command handler. This looks weird as command handlers are inherently void. Also, this produces a lot of completely unnecessary duplication and noise. If I have 100 command handlers I will have 100 “return Nothing.Value;” statements which don’t add anything (just noise). IMHO, better solution will be to augment Dispatcher, ie add second registration method for Actions -> https://gist.github.com/yevhen/7682490

    • Posted November 27, 2013 at 9:25 pm | Permalink | Reply

      It could be but you are forgetting that there are lots of compositions that you want to make as well. Say logging? Exception handling, transactions? You now need to duplicate all for action and func

  2. Posted November 27, 2013 at 10:41 pm | Permalink | Reply

    Yes, you’re right. Thus the number of such a cross-cutting concerns is usually < 10 (I'm speaking from the experience of medium-to-large project finished recently, which was using CQRS\ES). So you will have additional 10 overloads for void actions. It's an order of magnitude difference compared to possible duplication if using "return Unit;" in system with hundreds of command handlers.

    • Posted November 28, 2013 at 11:23 am | Permalink | Reply

      Another alternative is:

      x => { f(x); return Nothing.Value; }

      use this in a convenience method on register eg

      void Register(Action f) {
      Register(x=>{f(x); return Nothing.Value;});
      }

      Then all compositional pieces still operate on a func

      Cheers,

      Greg

  3. Posted November 28, 2013 at 11:33 am | Permalink | Reply

    updated the gist here : https://gist.github.com/gregoryyoung/7690486

  4. Kim
    Posted December 19, 2013 at 11:12 pm | Permalink | Reply

    Greg, I can follow the code in your gist, but I cannot figure out how to implement the decorator pattern as you mentioned in your talk. How would you wrap the dispatcher to add logging, transactions etc around each message call ?

    • Leif Battermann
      Posted March 4, 2014 at 8:43 am | Permalink | Reply

      Suppose this is the log method:
      public static void LogDoBar(Action log, DoBar command, Action next)
      {
      log(String.Format(“{0} called”, command.GetType().Name));
      next(command);
      }

      You can add it to the DoBar Command like this:
      _dispatcher.Register(message => Logging.LogDoBar(Console.WriteLine, message, x => CommandHandlers.Bar(() => new SqlConnection(), message)));

      I hope this helps 🙂

      • Leif Battermann
        Posted March 4, 2014 at 8:50 am | Permalink

        For some reason, the generic type parameters where formatted out. log has a string as a generic input type parameter and next and Register have DoBar.

  5. Posted February 24, 2014 at 10:54 pm | Permalink | Reply

    Hello, thanks for this interesting post. So for all the different return types of the (query) handlers in my application I am going to need a separate instance of Dispatcher? It would be nice to have just one but I don’t see how to do that. I don’t like to pass around lots of instances to other modules so much. Then I could better just pass several Func’s. Is there a solution to this? And something else, what is the interface Message for?

    • Posted March 2, 2014 at 2:17 pm | Permalink | Reply

      You would not need separate dispatchers just return “message” as example then you can use the same trick as in comments to allow for handlers to return individual messages (eg wrap the handler in dispatcher with a function that calls it and takes it result to return as Message)

      • Leif Battermann
        Posted March 5, 2014 at 8:52 am | Permalink

        I still don’t quite get it. I could manage by returning a class that implements the Result interface but then I have to up cast which I don’t like. Especially because I don’t always want to look up what return type the command handlers have. Also I can only return custom types and not string e.g. This is what I tried: https://gist.github.com/battermann/9363477 Do have a better way? Thanks.

      • Posted March 6, 2014 at 11:06 am | Permalink

        public static void Main()
        {
        Initialize();
        _dispatcher.Dispatch(new DoBar());
        _dispatcher.Dispatch(new DoFoo());

        var result1 = (FooBarResult)_dispatcher.Dispatch(new DoFooBar()); // either cast
        Console.WriteLine(result1.Value);

        var result2 = _dispatcher.Dispatch(new DoFooBar()); // or use generics
        Console.WriteLine(result2.Value);

        var result3 = _dispatcher.Dispatch(new DoBarFoo()); // doesn’t work
        Console.WriteLine(result3);
        }

        You get it back as your interface say “Message”. Very often the next part of the pipeline would be to do something like put it over http as a response which doesn’t need to interact with a concrete type.

        Another way of handling this if you want concrete types is to use an extension method named As() which would handle the casting for you.

        Cheers,

        Greg

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: