In the v3 version of Azure Functions DI is better supported and there’s now some offical documentation demonstrating how it’s done.
It’s pretty similar to how it was done previously, below is updated code from my previous v2 example.
using System;
using Serilog;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.DependencyInjection;
namespace JsonPlaceHolderDependencyInjection
{
public class Startup : FunctionsStartup
{
public Startup()
{
// Initialize serilog logger
Log.Logger = new LoggerConfiguration()
.WriteTo.Console(Serilog.Events.LogEventLevel.Debug)
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.CreateLogger();
}
public override void Configure(IFunctionsHostBuilder builder)
{
ConfigureServices(builder.Services).BuildServiceProvider(true);
}
private IServiceCollection ConfigureServices(IServiceCollection services)
{
services
.AddLogging(loggingBuilder =>
loggingBuilder.AddSerilog(dispose: true)
)
.AddTransient<IJsonPlaceholderClient, JsonPlaceholderClient>(client =>
new JsonPlaceholderClient(Environment.GetEnvironmentVariable("BaseAddress"))
)
.AddTransient<IJsonPlaceholderService, JsonPlaceholderService>();
return services;
}
}
}
The IFunctionsHostBuilder instance is created by the Azure functions host and passed into the Startup class so I don’t believe it’s possible to control how this is created as it is with a WebHost using the CreateDefaultBuilder method.
0 Comments