Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# DOTNET Dependency Injection Order Clarification

I do not get the behaviour of DI in the following case.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.Extensions.Azure;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Azure.Identity;

namespace TestResults.Processor;


internal class Program
{

    private static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", false, true)
            .AddEnvironmentVariables()
            .Build();

        var services = new ServiceCollection();
       

        services.AddLogging(configure =>
        {
            configure.AddConfiguration(configuration.GetSection("Logging"));
            configure.AddConsole();
        });

        services.ConfigureAndInjectServices(configuration);

        using var serviceProvider = services.BuildServiceProvider();

        var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogInformation($"serviceBusFqns: ....");
        logger.LogInformation($"serviceBusFqns: ....");

    }

   
}

public static class DependencyInjectionHelper
{
    public static void ConfigureAndInjectServices(this IServiceCollection services, IConfigurationRoot configuration)
    {

        var serviceBusFqns = configuration.GetValue<string>("ServiceBus:FullyQualifiedNs");
        var managedIdentityClientID = configuration.GetValue<string>("ServiceBus:ManagedIdentityClientID");

        services.AddAzureClients(builder =>
        {
            builder.AddServiceBusClientWithNamespace(serviceBusFqns);
            builder.UseCredential(new DefaultAzureCredential());
        });

    }
}

I am able to see the logs produced on Console. But if I swap the order of these lines:

services.ConfigureAndInjectServices(configuration);

services.AddLogging(configure =>
{
    configure.AddConfiguration(configuration.GetSection("Logging"));
    configure.AddConsole();
});

the log does not log anymore (to Console). Why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think this happens due to the following:

AddAzureClientsCore which is invoked by AddAzureClients tries to register NullLoggerFactory as ILoggerFactory:

collection.TryAddSingleton<ILoggerFactory, NullLoggerFactory>();

While AddLogging will try to add add LoggerFactory as one:

services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());

TryAdd{...} methods will add the registration only if the service type hasn’t already been registered so the first one called wins (unlike with the Add{...} methods which will result in the last one wins).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading