How To integrate Dependency Injection In Azure Functions

In this article, we are going to learn how to integrate Dependency Injection into Azure functions. We will also create a simple HTTP trigger Azure function and CustomerService and then we will inject the service object into the function using DI.

If you are new to Azure functions then first check the below articles.

In this article, we will discuss the below topics.

  • What is the Dependency Injection pattern?
  • Steps to add Dependency Injection in Azure Functions.

What is the dependency injection pattern?

Dependency Injection is a software design pattern that is used to make a class independent of its dependencies and helps to achieve the Inversion of Control (IOC) and loose coupling between classes and their dependencies. 

According to wiki

In software engineering, dependency injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. In the typical "using" relationship the receiving object is called a client and the passed (that is, "injected") object is called a service.

To learn more about dependency injection you can refer to this article. We can add dependency injection in Azure function similar to ASP.NET Core. If you want to learn more about dependency injection in ASP.NET core then you can refer to this article

So in this article, we will discuss how to add dependency injection into Azure functions.

Steps to add dependency injection in Azure Functions

Prerequisites

Create a simple HTTP trigger Azure Function

So open Visual Studio and Go to File -> New -> Project. Search "Azure Functions" in the search box select the Azure function template and click on Next.

Azure Function

Give a name to the function project and click on Create.

Click on create

Select the HTTP trigger template set the Authorization level as Anonymous and click on Create.

Http trigger

That's it. We have created our first Azure function. Open the Function1.cs file to see the generated function.

Generated function

Create a simple CustomerService that returns mock customer data

So right-click on solution -> Add -> New Project and then select .NET Standard class library and click on Next. Then give the name and finally click on Create.

Click on create

Now create a class called Customer with the below properties.

public class Customer
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string Country { get; set; }
}

Now create an interface called ICustomerService.cs as below.

using System.Collections.Generic;
namespace AzureFuncDependencyDemo.Customer.Service
{
    public interface ICustomerService
    {
        List<Customer> GetCustomersData();
    }
}

Finally, create a class that implements the ICustomerService interface's "GetCustomersDataAsync" method and returns a list of Customers.

using System.Collections.Generic;
namespace AzureFuncDependencyDemo.Customer.Service
{
    public class CustomerService : ICustomerService
    {
        public List<Customer> GetCustomersData()
        {
            var customersData = new List<Customer>();
            customersData.Add(new Customer()
            {
                Id = 101,
                Name = "Customer1",
                Country = "India"
            });
            customersData.Add(new Customer()
            {
                Id = 102,
                Name = "Customer2",
                Country = "USA"
            });
            return customersData;
        }
    }
}

Inject CustomerService into the Azure function to get customer data

First, we need to install the below Nuget package into the Azure function project.

Microsoft azure function extensions

Microsoft extension dependency

To inject dependency we first need to create a new class called "Startup. cs" into the root of the project. Add the below code into the class which is used at the start of the function app.

using AzureFuncDependencyDemo;
using AzureFuncDependencyDemo.Customer.Service;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(Startup))]
namespace AzureFuncDependencyDemo
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddTransient<ICustomerService, CustomerService>();
        }
    }
}
  • Then FunctionStartup attribute is used to register the assembly which specifies the name you need to use during the startup of the function.
  • Initiate  FunctionStartup and implement the Configure method to register all the dependencies.
  • Register ICustomerService dependency in the same way we usually do in ASP.NET core apps.

Now add the below code into the function to inject dependency and get the customer data.

using System.Threading.Tasks;
using AzureFuncDependencyDemo.Customer.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace AzureFuncDependencyDemo
{
    public class Function1
    {
        private readonly ICustomerService customerService;

        public Function1(ICustomerService _customerService)
        {
            customerService = _customerService;
        }
        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
        {
            var customersData = await customerService.GetCustomersDataAsync();
            return new OkObjectResult(customersData);
        }
    }
}

Now to run the function app we need to just run the project. It will then start Azure function cli to run the function.

Azure function cli

The function is running on 'http://localhost:7071/api/Function1'.

Function is running

That's it. We have now configured dependency injection into the Azure function app. 

If we want to use HttpClient to make an HTTP request then we can inject the HttpClient dependency in the same way we like adding it into NET Core. So let's add the below Nuget package,

Microsoft extension http

After that open Startup.cs class and add the below line to inject HttpClient dependency.

using AzureFuncDependencyDemo.Customer.Service;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(AzureFuncDependencyDemo.Startup))]
namespace AzureFuncDependencyDemo
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
            builder.Services.AddTransient<ICustomerService, CustomerService>();
        }
    }
}

Now create another Azure function and use the HttpClient to fetch the user's data using the 'jsonplaceholder.typicode.com/users' mock api. Right-click on the solution and click on Add -> New Azure Function.

Name Azure function

Select the Azure function give it the name "GetUsers" and click on the Add button.

Azure function

Select function trigger type as HttpTrigger and Authorization level as Anonymous. 

Http trigger

Now add the below code to fetch the user's data.

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace AzureFuncDependencyDemo
{
    public class GetUsers
    {
        private readonly HttpClient _httpClient;
        public GetUsers(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }
        [FunctionName("GetUsers")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var responseMessage = await _httpClient.GetAsync("http://jsonplaceholder.typicode.com/users");
            var usersData = responseMessage.Content.ReadAsStringAsync().Result;
            return new OkObjectResult(usersData);
        }
    }
}

Here we have injected HttpClient dependency using Constructor and then called the GetAsync method to fetch data from api. So run the application and see the output.

Run the application

Conclusion

In this article, we have created a new Azure function and a simple mock CustomerService from Visual Studio. Also, I demonstrated how to inject CustomerService dependency into the Azure function app and also inject it into the function. I hope that you enjoy this article, share it with friends, and please do not hesitate to send me your thoughts or comments.

Stay tuned for more Azure Functions articles.

You can follow me on Twitter @sumitkharche01 and Sumit Kharche

Happy Coding!