How to use dependency injection in Azure Functions

How to use dependency injection in Azure Functions

In this Azure tutorial, we will discuss the simple steps to integrate dependency injection into  Azure Functions with an example. Along with this, we will also discuss the below topics.

  • What is Dependency Injection?
  • Deploy The Dependency Injection-Based Azure Functions

Before starting the actual discussion, we should know What is Dependency Injection? and how it relates to Azure Function.

What is Dependency Injection?

Well, As we all know Dependency Injection is an excellent software design pattern. That helps for the maintainability of the Software. When you are using dependency injection, then it allows you for easier maintainability, testability, Code Reusability, Readability, and Flexibility.

 Azure Function Dependency Injection

Coming to the dependency Injection in the case of Azure Function, Azure Function supports the Dependency Injection software design pattern. This is one of the latest features of the Azure Function to support the Dependency Injection Software Design Pattern. Dependency Injection is used to create loosely coupled modules of code.

Now here is the improvement after the Dependency Injection has been introduced, so as per this software design pattern, a single object will be created and can be accessed by all the modules. No need to create separate objects for each module. Code maintenance will be easier compared to the earlier approach.

How to use dependency injection in Azure functions

Less discuss an example.

The scenario I’m implementing Dependency Injection is, I will create TSinfoEmployeeDetails Azure Function App, where we will validate the Employee whether belong to TSinfo or not based on the Email ID they will provide. If the Email ID contains @tsinfo.com then the email id is valid and the employee belongs to the TSinfo else the Employee is not part of the TSinfo company.

Before starting the actual functionality, we should know what are the prerequisites needed here to work with this functionality.

Prerequisites

Below are the prerequisites needed here to start with the development activity.

  1. Make sure you have an Azure Subscription or Azure Account. If you don’t have one, you can create an Azure Free account now.
  2. You must install Visual Studio 2019 with Azure Development workload in your development machine. If you have not yet installed it, you can install Visual Studio 2019 on your machine now.
  3. Basic Knowledge of C# language.

Assuming, you have all the prerequisites needed here, let’s start with the functionality by creating a new Azure Function Project. We will discuss the simple steps to add Dependency Injection in Azure Functions with C#.

Creating an HTTP trigger Azure function

Step-1: Open Visual Studio 2019, and click on Create a new Project button as shown below.

How to configure azure function dependency injection

Step-2: Now search for the Azure Functions template and choose the Azure Functions on the Create a new project window and then click on the Next button to go to the next screen.

c# azure function dependency injection

Step-3: Enter your Project name, and choose a location for your Azure function project On the Configure Your new Project window, and then click on the Create button.

azure functions v1 dependency injection

Step-4: We need to choose the trigger for our Azure Function, Let’s choose the Http trigger as the trigger option and select the  Storage Emulator  For the Storage Account (AzureWebJobsStorage) option, and choose the Function as Authorization level   On the Create a new Azure Functions Application window. Now click on the Create button to create the Azure Function as shown below.

how to use Dependency Injection in Azure Functions V3 using .NET Core and C#

Step-6: You can see below, the project got created successfully.

Why Dependency Injection in AzureFunction?

Step-7: Now let’s create our Interface. Add a class named as IEmployeeService.cs and then click on the Add button.

dependency injection in azure functions v3

Now add the below lines of code in the IEmployeeService.cs file

namespace TsinfoEmployeeDetails
{
    public interface IEmployeeService
    {
        string EmployeeEmail (string employeeEmailID);
    }
}
azure function dependency injection example

Step-8: Now, add a class named as EmployeeService.cs

using dependency injection in azure function

Now add the below lines of code in the EmployeeService.cs file

using System;
using System.Collections.Generic;
using System.Text;

namespace TsinfoEmployeeDetails 
{
    public class EmployeeService : IEmployeeService
    {
        public  string EmployeeEmail(string employeeEmailID)
        {
           
                if (employeeEmailID != null && employeeEmailID.Contains("@tsinfo.com"))
                    return "Valid EmailID";
                else
                    return "Invalid EmailID";
          
        }
    }
}
azure function dependency injection configuration

Step-9: Now the next step is we need to add a Startup assembly class file to the Project.

Before adding that class file, we need to install the Below Nugget packages as the dependencies as the prerequisites

  • Azure.Functions.Extensions (Latest Version)
  • Microsoft.NET.Sdk.Functions (Latest Version)
  • Extensions.Http (Latest version)

To add the Azure.Functions.Extensions, Right-click on the project –> Manage Nugget Packages –> search for the Azure.Functions.Extensions and Click on the search result, select the latest version –> Finally, click on the Install button to install the Azure.Functions.Extensions nugget package.

function app dependency injection

Same way, add Microsoft.NET.Sdk.Functions

dependency injection azure functions

Then, install Extensions.Http

dependency injection in azure functions v3

Now we need to add the Startup class which will inherit FunctionStartup, this is the place where the Dependency Injection will be implemented.

We need to add the below two using statements. To get the reference for the using statements, you need to install the prerequisites as mentioned above.

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

azure function app dependency injection

Constructor Injection

Below is the Code for the Startup.cs class file.

After our namespaces section in the below code, we have to add the FunctionsStartup attribute for the assembly.

The below line of code we need to add

[assembly: FunctionsStartup(typeof(TsinfoEmployeeDetails.Startup))]
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[assembly: FunctionsStartup(typeof(TsinfoEmployeeDetails.Startup))]
namespace TsinfoEmployeeDetails
{
    public class Startup: FunctionsStartup
    {

        public override void Configure(IFunctionsHostBuilder builder)
        {

            builder.Services.AddSingleton<IEmployeeService, EmployeeService>();
            
        }
    }
}

In the above code, The singleton service will instantiate the EmployeeService for a single time and it can be accessed by any object that injects the IEmployeeService in its Constructor.

azure functions dependency injection options

We need to do the below changes for the Function1.cs file, here we need to do the implementation of the Azure Function.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace TsinfoEmployeeDetails
{
    public  class Function1
    {
        private readonly IEmployeeService employeeService;
        public Function1(IEmployeeService employeeService)
        {
            this.employeeService = employeeService;
        }
        [FunctionName("TsinfoEmployeeDetails")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string empemail = req.Query["employeeEmailID"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            empemail = empemail ?? data?.empemail;

           
        string response = employeeService.EmployeeEmail(empemail);
                return response == "Valid EmailID"
                ? (ActionResult)new OkObjectResult($"TSINFO Valid Employee")
                : new BadRequestObjectResult("Invalid Employee.Not belongs to TSINFO");

          
        }
    }
}

If you will see the above code, we have defined the IEmployeeService Interface in the Constructor that will instantiate the EmployeeService in the runtime.

azure function logger dependency injection

Now Just to make sure everything is working, Let’s run the Azure function Project. You can able to see, it ran successfully without any issue, I got the function URL as below. The URL as below

http://localhost:7071/api/TsinfoEmployeeDetails

Dependency Injection in Azure Functions

Now to make sure the functionality is working fine, I tried accessing the function URL in the Browser with the employeeEmailID parameter value as the query string parameter like below

http://localhost:7071/api/TsinfoEmployeeDetails?employeeEmailID=rk@tsinfo.com

You can see below, I got the expected output “TSINFO Valid Employee”

azure function app dependency injection configuration

Now when I passed a wrong email id as a parameter, I got the expected output as “Invalid Employee. Not belongs to TSINFO”.

azure function timer trigger dependency injection

Deploy The Dependency Injection-Based Azure Functions

Well, Let’s discuss here the steps for Deploying The Dependency Injection Based Azure Functions using Visual Studio 2019.

Step-1: Right-click on the project name from Solution Explorer and select the “Publish” Option like below.

Deploy The Dependency Injection Based Azure Functions

Step-2: Choose the Azure Functions Consumption Plan and then you can select the Existing plan if you have or Choose the Create New option On the Pick a publish target window and now click on the Create Profile button to create the new Azure Functions Consumption Plan.

Deploying the Azure Function using Visual Studio 2019

Step-3: Provide a name, choose the subscription, and Choose your existing Resource group or you can create a new one by clicking on the new link, Selecting the Location, and then choosing your Existing Storage Account or if you don’t have an existing storage account, you can click on the New button to create a new Azure Storage Account and then finally click on the Create button.

Deploying the Azure Function from Visual Studio 2019

Step-4: Now you can see, it created a publish Profile successfully, Now click on the Publish button.

configuration azure function dependency injection

Step-5: Then click on the Yes button on the below Popup. Now it will deploy the Azure Function Successfully in Azure.

Deploy the Azure Function using Visual Studio

Step-6: Finally, To crosscheck that the Azure function is successfully Published to Azure, you can log in to the Azure Portal and navigate to the App services to check if the function app that you published from Visual Studio 2019 is present there. Now you can see below, the highlighted function app which we have deployed now.

Deploying the Azure Function using Visual Studio

This is all about how to implement Azure Function Dependency Injection as mentioned above.

You may also like following the below Articles

Conclusion

Well, in this article, we discussed, Azure Function Dependency Injection and then also discussed how to use dependency injection in Azure functions, and finally, we discussed. Deploy The Dependency Injection-Based Azure Functions. Hope you will enjoy this article.