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;

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.


2 Comments

Prem Mukherji · 3rd July 2020 at 11:40 am

You are referring FunctionsStartup and then you are inheriting from IWebJobsStartup? Why?

    Shinigami · 3rd July 2020 at 11:57 am

    Ah, that was left in from my previous code before FunctionsStartup wass avilable. I’ve updated the example now, thanks for pointing it out.

Leave a Reply to Prem Mukherji Cancel reply

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