Azure Functions Dependency Injection with injection config

yu_ka1984
2 min readJan 28, 2018

--

I often use Azure Functions recently. However, I am dissatisfied that the Dependency Injection environment at Azure Functions is incomplete, I searched Github’s Issue and found the next Issue.

And I read the blog of Boris Wilhelms.

This idea is so fantastic.

Before reading this blog , I was thinking of Dependency Injection using AutoFac. But I learned from this blog what using Microsoft.Extentions.DependencyInjection is appropriate as a Microsoft ecosystem .

Even with this idea, I could cope with what I wanted to realize, but I felt that I wanted to set the Dependency Injection outside the InjectConfiguration class.

I came up with an idea to set DI in function. And I forked this repository and added the code.

In this idea, specify the FunctionName that performs DI setting in the constructor of InjectAttribute.

A function for performing DI setting is created by attaching InjectConfigurationTriggerAttribute to the IServiceCollection parameter.

Please see this class for details on how to use it.

https://github.com/yuka1984/azure-function-dependency-injection/blob/InjectConfigTrigger/DependencyInjection/GreeterFunction.cs

Actually this code work.

IServiceCollection and IServiceProvider are managed in ConcurrentDictionary using FunctionName as a key and using the Lazy class. Executor of Config function is executed by FactoryMethod of Lazy.

Executor registration is done within the CreateListenerAsync method of the InjectConfigurationTriggerBinding class which is the implementation of the ITriggerBinding interface.

Then we call the IServiceProvider with the BindAsync method of the InjectBinding class to perform the injection.
As Lazy wraps calls to Executor, the Config function is called only once and exclusive control is also done.

Thank you for reading.

--

--

yu_ka1984

Microsoft MVP Azure Technologies / https://github.com/yuka1984 / Xamarin / .NET / ASP.NET Core / Web Front End / Azure