TIP

🔥 Make sure you star the repo (opens new window) to keep up to date with new tips and tricks.

💡 Learn more : Azure Functions overview (opens new window).

📺 Watch the video : How to use dependency injection in Azure Functions (opens new window).

# How to use dependency injection in Azure Functions

# Use dependency injection for code reuse and readability

When you are creating an application, you'll use different services and utilities throughout your classes. Some of these can have complex constructors, and some have dependencies on each other. By using dependency injection (opens new window), you make it easy for classes to receive an instance of a service and use it, without having to instantiate it. This makes your code more readable, and enables you to reuse services easier.

You can use the dependency injection pattern in Azure Functions (opens new window) that run on .NET. In this post, we'll see how that works.

# Prerequisites

If you want to follow along, you'll need the following:

# Implement the dependency injection pattern in .NET Azure Functions

We'll start by creating an Azure Function with Visual Studio. You can also use VS Code for this if you prefer.

  1. In Visual Studio, create a new project
  2. Choose Azure Functions as the project template
  3. Give the project a Name
  4. Click Create
  5. Next, select Http trigger and leave the rest of the settings as they are
  6. Finally, click Create to create the project

(Create an Azure Functions project in Visual Studio)

To demonstrate the use of dependency injection, we'll add some files to the Azure Functions project. These contain an interface, a service that implements that interface, and a Startup class that configures dependency injection.

  1. Create a new file called ITipsService.cs and paste the code below into it
    public interface ITipService
    {
        string GetTip();
    }
1
2
3
4
  1. Next, create a file called TipService.cs. Paste the following code into the file. This implements the ITipService. The GetTip method returns an Azure Tips and Tricks URL (opens new window) for a random tip.
    public class TipService : ITipService
    {
        public string GetTip()
        {
            Random tipNumber = new Random();

            return "https://microsoft.github.io/AzureTipsAndTricks/blog/tip" + tipNumber.Next(1, 335) + ".html";
        }
    }
1
2
3
4
5
6
7
8
9
  1. Finally, create a file and name it Startup.cs. Paste the following code in it, and make sure that you change references to the namespace "FunctionApp1" to the namespace of your Function App. This code adds the HttpClient service to the app, and the TipsService. By declaring them here, we can use them with dependency injection throughout the rest of the application. Note that the Function App can only contain one class that inherits from FunctionsStartup.
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(FunctionApp1.Startup))]

namespace FunctionApp1
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();

            builder.Services.AddSingleton<ITipService>((s) => {
                return new TipService();
            });
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

The project should now look something like this:

(The Azure Function project in Visual Studio)

  1. The startup class contains types from NuGet packages that you need to install. Right-click the project file and click Manage NuGet packages
  2. Click Browse
  3. Search for Microsoft.Azure.Functions.Extensions and install it
  4. Do the same for Microsoft.Extensions.Http
  5. Next, go to the Function class and change it into the code below:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Threading.Tasks;

namespace FunctionApp1
{
    public class Function1
    {
        private readonly HttpClient _client;
        private readonly ITipService _service;

        public Function1(IHttpClientFactory httpClientFactory, ITipService service)
        {
            this._client = httpClientFactory.CreateClient();
            this._service = service;
        }

        [FunctionName("Function1")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var url = _service.GetTip();
            var response = await _client.GetAsync(url);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new RedirectResult(url);
            }
            else
            {
                return new NotFoundResult();
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

This code uses a constructor to get an IHttpClientFactory and an ITipService injected into it. These are fully instantiated and ready to be used. That's the beauty of dependency injection. Next, it uses the TipService.GetTip method to retrieve the URL of an Azure Tips and Tricks post. It then uses the HttpClient to retrieve the website of the URL. If it exists, it will send a redirect request to that website, which sends the browser to the Azure Tips and Tricks post.

  1. Run the Function
  2. When the Function is running, it shows you the Function URL that you can use to trigger it. Copy the URL and paste in it a browser
  3. You'll be redirected to a post on the Azure Tips and Tricks website

(The Function redirects to an Azure Tips and Tricks post)

# Conclusion

Dependency injection (opens new window) is a software development pattern that makes code easier to read and reuse. You can use it in .NET Azure Functions (opens new window) by implementing a Startup class that uses the FunctionsStartup class to function. Go and check it out!