Azure Functions are very useful for hosting APIs in the cloud or for responding to asynchronous events in our cloud systems. Azure Functions also have a nice pricing model for startups; they can be priced on a per-consumption basis which can reduce monthly costs until you start to get real usage, which often takes longer than expected.
Microsoft has made Azure Functions super easy to create. You can create them within Visual Studio (or Visual Studio Code). Microsoft’s tooling is excellent because you get nice editors to set it up.
But the way they create Azure Functions could be better. First off, they create one file per Azure Function in your solution. That’s not an issue if you only have one Azure Function, but it can be problematic if you have many. However, you can get around this by putting multiple Azure Functions in the same file. Here’s how to do it.
First, create an Azure Function using Visual Studio’s Add dialog (this image is from Visual Studio Mac).
Then create an HTTP trigger function.
That should give you some boilerplate code.
This code makes everything static and assumes only one Azure Function per file. We will change that with a few small tweaks.
First, let’s make everything NOT static by using instance methods. This is an easy change to remove the “static”. We will now change to using constructor injection instead of injecting services in the Run method. These changes are pretty straightforward. You can see their results in the code below.
The above changes don’t get us to our goal of two functions in the same file. But that goal is now pretty easy. We add additional methods to our file for each function. See the code below.
Azure Functions have some nice features and advantages. But there are times when there is still some awkwardness in working with them. Hopefully this post helps you better structure your Azure Functions.