Dependency Injection in .NET Azure Function

Navneet Lal Gupta
1 min readMar 21, 2021

Dependency Injection (DI) enables the development of loosely coupled code. Through DI, you can decrease the tight coupling between software components. It is also known as Inversion-of-Control, which makes unit testing convenient. While following serverless, we usually forget about DI which is common because in serverless we only care about is a function and hence end up with tightly coupled code. This later effects unit testing of our serverless functions.

Azure Functions supports the dependency injection (DI) software design pattern and depending on the consumption plan you can override dependencies and change how configuration values are read.

Before you can use dependency injection, you must install Microsoft.Azure.Functions.Extensions and Microsoft.NET.Sdk.Functions package from NuGet. To register a service, first, create a Startup.cs file in the root directory of your project and create a Startup class which inherits FunctionsStartup. Later add the FunctionsStartup assembly attribute that specifies the type name used during startup. For reference have a look into the below code.

Within the Startup class, we create a Configure method to override the default one and add all the services we want to register, Like in my case its MongoDbContext.

Next step will be to use the injected dependency. We use constructor injection to make our dependency available in functions and to make that work we need to remove the static keyword (we can not use static class for function class while using DI) from the class or method.

And that’s it. Now you have mongoDbContext available to our lambda function. Similarly we can make Logger available too.

--

--