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 Dependency Injection pattern?
  • Steps to add Dependency Injection in Azure Functions.

What is Dependency Injection pattern?

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

According to wikki,
 
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 dependeny 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 and select the Azure function template and click on Next.
 
 
Give a name to the function project and click on Create.
 
 
Select the HTTP trigger template and set the Authorization level as Anonymous and click on Create.
 
 
That's it. We have created our first Azure function. Open the Function1.cs file to see generated function.
 
 

Create a simple CustomerService which 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 name and finally click on Create.
 
 
Now create class called Customer with the below properties,
  1. public class Customer  
  2. {  
  3.     public string Name { getset; }  
  4.     public int Id { getset; }  
  5.     public string Country { getset; }  
  6. }   
Now create a interface called ICustomerService.cs as below,
  1. using System.Collections.Generic;  
  2.   
  3. namespace AzureFuncDependencyDemo.Customer.Service  
  4. {  
  5.     public interface ICustomerService  
  6.     {  
  7.         List<Customer> GetCustomersData();  
  8.     }  
  9. }  
And finally create a class which implements ICustomerService interface's "GetCustomersDataAsync" method and returns a list of Customers.
  1. using System.Collections.Generic;  
  2.   
  3. namespace AzureFuncDependencyDemo.Customer.Service  
  4. {  
  5.     public class CustomerService : ICustomerService  
  6.     {  
  7.         public List<Customer> GetCustomersData()  
  8.         {  
  9.             var customersData = new List<Customer>();  
  10.             customersData.Add(new Customer()  
  11.             {  
  12.                 Id = 101,  
  13.                 Name = "Customer1",  
  14.                 Country = "India"  
  15.             });  
  16.   
  17.             customersData.Add(new Customer()  
  18.             {  
  19.                 Id = 102,  
  20.                 Name = "Customer2",  
  21.                 Country = "USA"  
  22.             });  
  23.             return customersData;  
  24.         }  
  25.     }  
  26. }  

Inject CustomerService into Azure function to get customer data

 
First we need to install the below nuget package into Azure function project,
 
 
 
To inject dependency we first need to create a new class called as "Startup.cs" into the root of the project. Add the below code into class which is used at the start of the function app.  
  1. using AzureFuncDependencyDemo;  
  2. using AzureFuncDependencyDemo.Customer.Service;  
  3. using Microsoft.Azure.Functions.Extensions.DependencyInjection;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. [assembly: FunctionsStartup(typeof(Startup))]  
  7.   
  8. namespace AzureFuncDependencyDemo  
  9. {  
  10.     public class Startup : FunctionsStartup  
  11.     {  
  12.         public override void Configure(IFunctionsHostBuilder builder)  
  13.         {  
  14.             builder.Services.AddTransient<ICustomerService, CustomerService>();  
  15.         }  
  16.     }  
  17. }  
  • Then FunctionStartup attribute is used to register the assembly which specifies the name you need to used during startup of 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 function to inject dependency and get the customer data.
  1. using System.Threading.Tasks;  
  2. using AzureFuncDependencyDemo.Customer.Service;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Azure.WebJobs;  
  6. using Microsoft.Azure.WebJobs.Extensions.Http;  
  7.   
  8. namespace AzureFuncDependencyDemo  
  9. {  
  10.   
  11.     public class Function1  
  12.     {  
  13.         private readonly ICustomerService customerService;  
  14.   
  15.         public Function1(ICustomerService _customerService)  
  16.         {  
  17.             customerService = _customerService;  
  18.         }  
  19.   
  20.         [FunctionName("Function1")]  
  21.         public  async Task<IActionResult> Run(  
  22.             [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)  
  23.         {  
  24.             var customersData = await customerService.GetCustomersDataAsync();  
  25.   
  26.             return new OkObjectResult(customersData);  
  27.         }  
  28.     }  
  29. }  
Now to run the function app we need to just run the project. It will then start Azure function cli to run the function.
 
 
The function is running on 'http://localhost:7071/api/Function1'
 
 
That's it. We have now configured dependency injection into Azure function app. 
 
If we want to use HttpClient to make a http request then we can inject the HttpClient dependency in the same way we like adding into NET Core. So let's add the below nuget package,
 
 
After that open Startup.cs class and add below line to inject HttpClient dependency.
  1. using AzureFuncDependencyDemo.Customer.Service;  
  2. using Microsoft.Azure.Functions.Extensions.DependencyInjection;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. [assembly: FunctionsStartup(typeof(AzureFuncDependencyDemo.Startup))]  
  6.   
  7. namespace AzureFuncDependencyDemo  
  8. {  
  9.     public class Startup : FunctionsStartup  
  10.     {  
  11.         public override void Configure(IFunctionsHostBuilder builder)  
  12.         {  
  13.             builder.Services.AddHttpClient();  
  14.             builder.Services.AddTransient<ICustomerService, CustomerService>();  
  15.         }  
  16.     }  
  17. }  
Now create another azure function and use the HttpClient to fetch user's data using 'jsonplaceholder.typicode.com/users' mock api. Right click on solution and click on Add -> New Azure Function.
 
 
Select Azure function and give it name "GetUsers" and click on Add button.
 
 
Select function trigger type as HttpTrigger and Authorization level as Anonymous. 
 
 
Now add the below code to fetch user's data. 
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Azure.WebJobs;  
  6. using Microsoft.Azure.WebJobs.Extensions.Http;  
  7. using Microsoft.Extensions.Logging;  
  8.   
  9. namespace AzureFuncDependencyDemo  
  10. {  
  11.     public class GetUsers  
  12.     {  
  13.         private readonly HttpClient _httpClient;  
  14.         public GetUsers(HttpClient  httpClient)  
  15.         {  
  16.             _httpClient = httpClient;  
  17.         }  
  18.   
  19.         [FunctionName("GetUsers")]  
  20.         public async Task<IActionResult> Run(  
  21.             [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,  
  22.             ILogger log)  
  23.         {  
  24.             log.LogInformation("C# HTTP trigger function processed a request.");  
  25.   
  26.             var responseMessage = await _httpClient.GetAsync("http://jsonplaceholder.typicode.com/users");  
  27.             var usersData = responseMessage.Content.ReadAsStringAsync().Result;  
  28.             return new OkObjectResult(usersData);  
  29.         }  
  30.     }  
  31. }   
Here we have inject HttpClient dependency using Constructor and then call GetAsync method to fetch data from api. So run the application and see the output.
 
 

Conclusion

 
In this article, we have created a new Azure function and simple mock CustomerService from Visual Studio. Also, I demonstrated how to inject CustomerService dependency into Azure function app and also inject it into function. I really 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!