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?
>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).