DI in Azure Functions DI in Azure Functions azure azure

DI in Azure Functions


There is an open feature request on the GitHub pages for Azure Functions concerning this matter.

However, the way I'm approaching this is using some kind of 'wrapper' entry point, resolve this using the service locator and and start the function from there.

This looks a bit like this (simplified)

var builder = new ContainerBuilder();//register my typesvar container = builder.Build();using(var scope = container.BeginLifetimeScope()){  var functionLogic = scope.Resolve<IMyFunctionLogic>();  functionLogic.Execute();}

This is a bit hacky of course, but it's the best there is until there is at the moment (to my knowledge).


I've seen the willie-zone blog mentioned a lot when it comes to this topic, but you don't need to go that route to use DI with Azure functions.

If you are using Version2 you can make your Azure functions non-static. Then you can add a public constructor for injecting your dependencies. The next step is to add an IWebJobsStartup class. In your startup class you will be able to register your services like you would for any other .Net Core project.

I have a public repo that is using this approach here: https://github.com/jedi91/MovieSearch/tree/master/MovieSearch

Here is a direct link to the startup class: https://github.com/jedi91/MovieSearch/blob/master/MovieSearch/Startup.cs

And here is the function: https://github.com/jedi91/MovieSearch/blob/master/MovieSearch/Functions/Search.cs

Hope this approach helps. If you are wanting to keep your Azure Functions static then the willie-zone approach should work, but I really like this approach and it doesn't require any third party libraries.

One thing to note is the Directory.Build.target file. This file will copy your extensions over in the host file so that DI will work once the function is deployed to Azure. Running the function locally does not require this file.