Alternative approach to HttpClient in Azure Functions 2.0 revisited - move to dependency injection

26 lis 2019 | Blog | azure functions | .net | dependency injection | azure | programowanie | IT

Recently I've received a question regarding my previous post on using HttpClient with Azure Functions. It made me realize that I'm long overdue with a follow-up because that's not the best approach anymore.

Moving to Dependency Injection

In my previous approach, I was creating an extension to leverage internally available dependency injection for the purpose of using HttpClientFactory. Back then it was the only way to use dependency injection in Azure Functions, but that's no longer the case. A few months ago Azure Functions has been given the first-class support for dependency injection. This means that extension is no longer needed, HttpClientFactory can be registered and used directly from the functions project level.

Registering services with Azure Functions dependency injection requires a startup class. This class must inherit from FunctionsStartup, which allows for overriding the Configure method. The Configure method will be passed an instance of IFunctionsHostBuilder by the host, with which we can register HttpClientFactory. In order for the host to find the startup class, there must be an assembly level FunctionsStartupAttribute pointing to it.

[assembly: FunctionsStartup(typeof(Startup))]

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

Consuming a service available through dependency injection requires instance-based approach to functions implementation. This is because Azure Functions supports constructor-based dependency in

POSTY TEGO AUTORA

Monitoring C# Azure Functions in the Isolated Worker Model - Infrastructure & Configuration Deep Dive26 lis 2024

Blog | programowanie | .net | c# | azure functions | IT

ASP.NET Core 9 and IAsyncEnumerable - Async Streaming JSON and NDJSON From Blazor WebAssembly24 wrz 2024

Blog | programowanie | .net | c# | asp.net core | blazor | IT

Azure Functions Extensibility - Extensions and Isolated Worker Model5 mar 2024

Blog | programowanie | .net | c# | azure functions | azure | IT

Azure Functions Extensibility - Runtime Scaling22 lut 2024

Blog | programowanie | .net | c# | azure | IT

Yet Another Developer Blog

noreply@blogger.com (Tomasz Pęczek)