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.

Startup.cs

using System;
using Serilog;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(Datofy.Function.Startup))]

namespace JsonPlaceHolderDependencyInjection
{
    public class Startup : IWebJobsStartup
    {
        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.


Leave a Reply

Your email address will not be published. Required fields are marked *