Azure Function Dependency Injection Example

How to use dependency injection in Azure Functions

This Azure tutorial will discuss the simple steps to integrate dependency injection into  Azure Functions with an example.

Azure Function Dependency Injection Example

Less discuss an example.

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

Before starting the actual functionality, we should know what 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 on 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

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

azure functions dependency injection

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

dependency injection azure functions

3. Enter your Project name, 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

4. We need to choose the trigger for our Azure Function; let’s choose the Http trigger as the trigger option, 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.

azure function di

6. You can see below that the project was created successfully.

azure function configuration dependency injection

7. Now, let’s create our Interface. Add a class named 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

8. Now, add a class named as EmployeeService.cs

azure durable functions dependency injection

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 c# dependency injection

9. The next step is adding 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 azure function

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 must install the prerequisites mentioned above.

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

azure function .net 6 dependency injection

Constructor Injection

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

After our namespaces section in the code below, 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 function dependency injection

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 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, to ensure everything is working, Let’s run the Azure function Project. You can see that it ran successfully without any issues; I got the function URL 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

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

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

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

Deploy The Dependency Injection Based Azure Functions

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

Deploying the Azure Function using Visual Studio 2019

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 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

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

configuration azure function dependency injection

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

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 you published from Visual Studio 2019 is present. 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 implementing Azure Function Dependency Injection, as mentioned above.

FAQs

What is Dependency Injection?

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 that supports 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. 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.

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. I hope you will enjoy this article.