- Print
- DarkLight
- PDF
Use Dependency Injection in Azure Functions
- Print
- DarkLight
- PDF
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.
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.
You can find various samples online; a basic self-explanatory one is available on GitHub.