7.5 KiB
type | title | excerpt | tags | share | date | |
---|---|---|---|---|---|---|
post | Tip 351 - How to use dependency injection in Azure Functions | Learn how to use dependency injection in Azure Functions |
|
true | 2022-02-02 08:00:00 |
::: tip
🔥 Make sure you star the repo to keep up to date with new tips and tricks.
💡 Learn more : Azure Functions overview.
📺 Watch the video : How to use dependency injection in Azure Functions.
:::
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, 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 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:
- An Azure subscription (If you don't have an Azure subscription, create a free account before you begin)
- The latest version of Visual Studio or VS Code
- Make sure to have the Azure workload enabled for Visual Studio
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.
- In Visual Studio, create a new project
- Choose Azure Functions as the project template
- Give the project a Name
- Click Create
- Next, select Http trigger and leave the rest of the settings as they are
- 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.
- Create a new file called ITipsService.cs and paste the code below into it
public interface ITipService
{
string GetTip();
}
- 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 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";
}
}
- 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();
});
}
}
}
The project should now look something like this:
(The Azure Function project in Visual Studio)
- The startup class contains types from NuGet packages that you need to install. Right-click the project file and click Manage NuGet packages
- Click Browse
- Search for Microsoft.Azure.Functions.Extensions and install it
- Do the same for Microsoft.Extensions.Http
- 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();
}
}
}
}
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.
- Run the Function
- 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
- 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 is a software development pattern that makes code easier to read and reuse. You can use it in .NET Azure Functions by implementing a Startup class that uses the FunctionsStartup class to function. Go and check it out!