Implementing Dependency Injection In Azure Functions

This article talks about how we can use dependency injection in Azure Functions. Dependency injection is a very well known design pattern that is used to implement IoC as provides you a facility to segregate object creation logic from its usage.

Prerequisites And Tools Used

In order to implement dependency injection in Azure Function App, you need an active Azure subscription, Visual Studio (I’m using Visual Studio 2019), and working knowledge of the C# language.

Create Function App in Visual Studio

The first step is to create a new project in Visual Studio of type Azure Functions:

and select Http Trigger as shown below:

Add Classes For Dependency Injection

Next we need to add the service (classes) which we want to inject. For simplicity, we will create an interface and a class implementing that interface. This interface will have only one method named GetCurrentTime() and it will provide current time to the caller. Here are the definitions:

public interface ICurrentTimeProvider
{
   DateTime GetCurrentTime();
}
public class CurrentTimeProvider : ICurrentTimeProvider
{
     public DateTime GetCurrentTime()
     {
         return DateTime.Now;
     }
}

Add Startup Class To Inject Dependency

We will add another class named Startup which will do all the dependency mapping task for us.

Here we need to pull in two Nuget packages as shown below:

Here is the code for Startup class:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using SampleFunctionApp.Services;
public class Startup : FunctionsStartup
{
   public override void Configure(IFunctionsHostBuilder builder)
   {
      builder.Services.AddHttpClient();
      builder.Services.AddSingleton<ICurrentTimeProvider>((s) => { return new CurrentTimeProvider(); });
    }
}

Update Function To Accommodate Dependency Injection

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SampleFunctionApp.Services;
using System.Net.Http;
using System.Threading.Tasks;
public class Function1
{
        private readonly HttpClient httpClient;
        private readonly ICurrentTimeProvider currentTimeProvider;

        public Function1(IHttpClientFactory httpClientFactory, ICurrentTimeProvider timeProvider)
        {
            httpClient = httpClientFactory.CreateClient();
            currentTimeProvider = timeProvider;
        }

        [FunctionName("Function1")]
        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.");
            var currentDateTime = currentTimeProvider.GetCurrentTime();
            StringContent content = new StringContent(JsonConvert.SerializeObject(currentDateTime.ToString()));
            var response = await httpClient.PostAsync("URL_TO_POST", content);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new OkObjectResult(response.Content);
            }
            else 
            {
                return new BadRequestObjectResult(response.StatusCode);
            }            
        }
}

Hope you enjoyed reading this article. You can also find the recording of this entire flow here.


Similar Articles