Azure Function Dependency Injection

Azure Function Dependency Injection

In this Azure tutorial, we will discuss Azure Function Dependency Injection. Along with this, we will also discuss the below topics.

  • What is Dependency Injection?
  • Way of Coding Before Dependency Injection
  • Why Dependency Injection?
  • Dependency Injection and Azure Functions
  • Creating A New Azure Function Project to implement Dependency Injection
  • Azure Function v3 Dependency Injection
  • Deploy The Dependency Injection Based Azure Functions

Azure Function Dependency Injection

Before starting the actual discussion on Azure Function Dependency Injection, we should know What is Dependency Injection?.

What is Dependency Injection?

Well, As we all know that 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.

Way Of Coding Before Dependency Injection

Earlier, the way of coding was different. Each module was having its Own objects of the main service class to access the properties and the methods. So the bonding between the service and the module was tightly coupled. Where the code maintenance was very challenging. In case, of Dependency Injection, the way of coding is totally different.

Azure Function Dependency Injection implementation

Why Dependency Injection?

Dependency Injection software design pattern has lots of benefits. Let’s discuss a few key benefits of the Dependency Injection design pattern.

Loosely coupled: The loosely coupled feature is one of the excellent benefits of Dependency Injection. Being loosely coupled, Updating the code is easier. It helps with the code maintainability.

Readability Of Code: With the help of the Dependency Injection, the readability of the code becomes easier as it moves all the dependencies to the main object.

Re-usability: This is another important feature of Dependency Injection. This is one of the reasons many people prefer implementing Dependency Injection in their Project structure.

Dependency Injection and Azure Functions

Azure Functions is basically a “Functions-as-a-service” that provides the solution to run a few lines of code (functions) in the cloud environment. No need to take any headache for the whole application or the infrastructure. You just need to worry about how to write the code. You can check out some more details on Azure Function.

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.

azure function dependency injection configuration

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 we have some understanding of the Azure Function, Dependency Injection. So now we will create a new Azure Function project and will implement the Dependency Injection for the project.

Creating A New Azure Function Project to implement Dependency Injection

The scenario I’m implementing Dependency Injection is, I will create TSinfoEmployeeDetails Azure Function App, where we will validate the Employee whether they 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.

Azure Function v3 Dependency Injection

Assuming, you have all the prerequisites needed here, let’s start with the functionality by creating a new Azure Function Project. we will see here the implementation of Dependency Injection in Azure Functions with C#.

Creating a simple HTTP trigger Azure function

Step-1: Open the Visual Studio 2019, 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.

Use dependency injection in .NET Azure Functions

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#
azure functions v3 dependency injection

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
function app dependency injection

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

namespace TsinfoEmployeeDetails
{
    public interface IEmployeeService
    {
        string EmployeeEmail (string employeeEmailID);
    }
}
Azure Functions Dependency Injection configuration
azure function v3 dependency injection

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";
          
        }
    }
}
use dependency injection in azure function
azure functions dependency injection

Add A Startup Class To The Azure Function

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

Azure Function Startup configuration

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
Azure Function v3 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 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
azure function 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 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, Choose your existing Resource group or you can create a new one by clicking on the new link, Select the Location and then choose 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 your 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 the 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, Azure Function Dependency Injection implementation with one example, What is Dependency Injection?, Way of Coding Before Dependency Injection, Why Dependency Injection?. and then we also discussed Dependency Injection and Azure Functions, Creating A New Azure Function Project to implement Dependency Injection, Azure Function v3 Dependency Injection, and finally, we discussed. Deploy The Dependency Injection Based Azure Functions. Hope you will enjoy this article.