Dependency Injection with .NET Azure Functions

  • Post published:May 23, 2020

.NET Azure functions supports the dependency injection design pattern by providing an extension package. Support for dependency injection begins with Azure Functions 2.x.

Getting started

Create an empty .NET Azure Function project named Demo. Install the following nuget package:


Create the following classes:

Registering services

Create a class called Startup. To indicate that this class is a startup class, the Startup class needs a FunctionsStartup assembly attribute:

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

The below code base presents a startup class:

To get access to the IServiceCollection for registering services, the Startup class needs to implement the FunctionsStartup abstract class. The configure method will allow services to be registered.

The startup class is now ready to register services. As an example, register the hero repository as follows:

Constructor injection is used to make dependencies available in a function. Note that when using constructor injection, ensure that the class and method are not static. Consider the below HTTP Trigger function using constructor injection:

Build and run the solution. Open postman and execute a get request using the heroes endpoint. As can be seen below, the list of heroes is received.


Azure Function apps provide the following service lifetimes:

  • Transient – transient services are created upon each request of the service.
  • Scoped – scoped service lifetime matches a function execution lifetime. Scoped services are created once per execution.
  • Singleton – singleton service lifetime matches the host lifetime and is reused across function executions on that instance.


Microsoft have made it very easy to use dependency injection in .NET Azure Functions by installing the following nuget package:


The source code used in this article can be found here.

Further information on dependency injection in .NET Azure Functions can be found at the following link:

Software versions used in this article

  • Visual Studio 2019 v4.8.03752
  • Microsoft.Azure.Functions.Extensions v1.0.0
  • Microsoft.NET.Sdk.Functions v3.0.7
  • .NET Core v3.1
  • Postman v7.24.0
  • ReSharper Ultimate v2020.1.1