Azure Functions and the mediator pattern (using MediatR)

Laurentiu Iarosevici
3 min readNov 23, 2021

Some time ago, I had this really interesting idea, how awesome would it be to use MediatR in functions. I played a bit around, got to the point where I got it to work, but to be honest it felt really really clumsy and awkward, so I kind of let it go. But recently, with the isolated process, things look a bit more promising, still it also feels a bit awkward, but bear with me.

Before we start, if you are not up to speed on MediatR, I recommend CodeOpinions post about it.

Now, the setting up of MediatR is rather simple in isolated functions, I mean :

That is it, no reason to even make a gist for this right ? But this opens up the main question that bothered me so much:

Why in the world would you use MediatR in functions ?

Me, thinking about this …

Now really, we already have quite a decent way of doing “flows” in the form of the durable functions, so why bother with yet another way of abstracting ?

Well, the first and most obvious reason is that, we can do it, and if it is possible, someone will do it right ? But this is not a real reason right ? Good, then why bother writing this article anyway if it is both easy to set up and a rather pointless or unhelpful exercise ? Well, I have another idea though, why we might want to use MediatR in functions.

Portability

Yep, think about this, you already use MediatR in your APIs, and everything is nice and dandy, but you realise that you have an api that actually has only one endpoint that is implemented with MediatR. And rather paying a full web app, or having a vm host this, you could run this almost for free (it depends, but yeah… ) as a function in consumption plan. So, how hard would be this to pull off ?

Actually really, easy. Let’s look into this.

Step 1 — Copy the Handler and Request code

Let’s say you have something like this in your Handler:

For minimising the length of the post, I will not include the Command and Output definitions, that is rather irelevant in our case (this is part of a future post that will explore building more complex scenarios).

Step 2 — Create the HTTP Handler function

Now, everything that you need to do, is to create a Function Handler (http, or whatever suits you to trigger this), basically, recreate your controller.

And to be honest, this is it, now you have the same “pipeline” of resolving HTTP requests, but in a Serverless fashion.

Conclusion

Well, to be honest, I still have rather mixed feelings about this, and I intend to explore this idea into more depth in the next couple of days and see what I can discover and come up with. But to be honest, this looks like a promising alternative to durable functions if the flows are rather “short lived” orchestrations and you don’t think you need the “pausing” functionality that is offered by orchestrators.

--

--