Use Dependency Injection in Azure Functions
  • 09 Sep 2022
  • 1 Minute to read
  • Contributors
  • Comment
  • Dark
    Light
  • PDF

Use Dependency Injection in Azure Functions

  • Comment
  • Dark
    Light
  • PDF

#ServerlessTips - Azure Functions
Author: Steef-Jan Wiggers Azure MVP

One of the latest additions to Azure Functions is the support for dependency injection (DI) – a technique to achieve what is called Inversion of Control (IoC) between classes and their dependencies. What the Microsoft Product Team has done is to build this capability on top of the ASP.NET Core Dependency Injection features. Furthermore, note that DI is only supported for version 2.x of Azure Functions.

To enable DI for your Azure Function, you will need to according to the documentation, install the following NuGet packages:

Microsoft.Azure.Functions.Extensions
Microsoft.NET.Sdk.Functions package version 1.0.28 or later
• Optional: Microsoft.Extensions.Http Only required for registering HttpClient at startup

Once you install these NuGet packages, you need to create a method to configure and add components to an IFunctionsHostBuilder instance – in runtime the host of your functions will create an instance of IFunctionsHostBuilder and passes it directly into your method.

code-1

The code above shows the registration of Microsoft.Azure.Cosmos from NuGet. After the registration, you can use the constructor injection to make your dependencies available to your function.

With the use of the constructor injection, you efficiently manage your dependencies – which is difficult when using static.

code-2

You can find various samples online; a basic self-explanatory one is available on GitHub.

Azure-functions.png


Was this article helpful?