Just before the Connect(); event, Azure Functions has become GA. Now more and more developers and IT pros are interested in it. One of the main attractions of using Azure Functions is, as a developer using C# codes, we can directly import existing private assemblies into Functions. In other words, we can easily migrate our existing applications to Azure Functions with minimal changes!
However, as we all know, migration is not that easy, especially if a huge architectural change is required. Once of the biggest challenges for the migration is probably “Managing Dependencies”. In this post, we are going to have a look which approach would be suitable for us to migrate applications smoothly.

We can find the source codes used in this post here: https://github.com/devkimchi/Azure-Functions-Dependency-Injections-Sample

Azure Function Structure

Let’s see the basic function structure. Here’s a function code when we create a manual trigger function:

What can we see here? That’s right. It’s a static method! That simply means our existing IoC container won’t fit here, if we use an IoC container for dependency management. So, what can we do here? We now need to consider a service locator pattern.

Autofac and CommonServiceLocator

If we use Autofac for our application’s dependency management, we need to create a service locator object using Autofac.Extras.CommonServiceLocator. Let’s see some code bits:

First of all, like what we are doing with Autofac, we just add dependencies using builder.RegisterType(). Then, we create an AutofacServiceLocator instance and put the instance to the service locator instance. That’s it! Let’s create a function.

Azure Functions with Service Locator

We don’t need to follow the whole step, but as a best practice that Azure Functions team suggests, we’re putting a private assemblies into the Shared folder using KUDU.

And create a .csx file within the Shared folder to create the service locator instance.

Now we have a static locator instance. We all set. Let’s create a function using this instance.

If we run this function, we get the result as expected.

This also works in an async function:

So far, we have a brief look how the service locator pattern works for our Azure Functions to manage dependencies. Migration to Azure Functions from our existing application wouldn’t be that easy, of course. However, we still use existing private assemblies as long as we introduce the service locator pattern for dependency management. Service locator pattern might be old-fashioned, but surely it’s working. There might be a better solution for managing dependencies. If you guys find anything better, let’s discuss here!

Category:
Application Development and Integration, Azure Platform
Tags:
, ,