Dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies, it allows to develop loosely coupled code.
Azure Functions supports for dependency injection (DI) started in 2.x, it is built on the .NET Core Dependency Injection features, so if you are used it, this should mostly look familiar to you.
Getting Started
Before you can use dependency injection, you must install the following NuGet packages in you Azure functions Projects
- Microsoft.Azure.Functions.Extensions
- Microsoft.NET.Sdk.Functions package version 1.0.28 or later
Create a class to register services, I called it startup, you can name it anything, create a method inside the class to configure and add components to an IFunctionsHostBuilder
instance. The Azure Functions host creates an instance of IFunctionsHostBuilder
and passes it directly into your method.
To register the method, add the FunctionsStartup
assembly attribute that specifies the type name used during startup.

Using Injected Dependencies
Constructor injection is used to make your dependencies available in a function. The use of constructor injection requires that you do not use static classes for injected services or for your function classes

Service lifetimes
Azure Functions apps provide the same service lifetimes as ASP.NET Dependency Injection.
- Transient: Transient services are created upon each request of the service.
- Scoped: The scoped service lifetime matches a function execution lifetime. Scoped services are created once per execution. Later requests for that service during the execution reuse the existing service instance.
- Singleton: The singleton service lifetime matches the host lifetime and is reused across function executions on that instance. Singleton lifetime services are recommended for connections and clients, for example DocumentClient or HttpClient instances.
Useful links
https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
Conclusion
DI is great to write loosely couple code and make it easier for implementing Unit Tests.
Thank you
Srinivasa Avanigadda
Dependency injection with Azure functions
Tweet