holly_cheng
holly_cheng

Reputation: 2481

Configure a logging provider for a different service collection

This is an ASP.NET application in .NET 6. There's a wizard interface where the user inputs some data and then based on the input, I set up a new dependency injection container with the services that are required to complete the task. My problem is that the ILogger<> instances coming out of this second container don't use the custom ILoggingProvider that I set up.

Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddDebug();
builder.Logging.AddSignalRLogging();
public static class ILoggingBuilderExtensions
{
    public static ILoggingBuilder AddSignalRLogging(this ILoggingBuilder builder) 
        => builder.AddProvider(new SignalRLoggerProvider(builder.Services))
           .AddFilter<SignalRLoggerProvider>("MyNamespace", LogLevel.Information);
}

The SignalRLoggerProvider comes from How to implement an ILogger to send messages to a SignalR Hub?.

Controller:

IServiceCollection services = new ServiceCollection();
services.AddLogging();
services.AddSignalR();
services.AddSingleton(_sheetsClient); // this was injected into the controller
services.AddSingleton<ITeamReaderService>(new PostedTeamReaderService(model.Divisions));

string[] divisionNames = model.Divisions.Keys.ToArray();
foreach (string divisionName in divisionNames)
{
    services.AddSingleton<IDivisionSheetService>(provider => new DivisionSheetService(divisionName,
        provider.GetRequiredService<StandingsRequestCreatorFactory>(),
        provider.GetRequiredService<ISheetsClient>(),
        provider.GetRequiredService<IOptionsMonitor<ScoreSheetConfiguration>>(),
        provider.GetRequiredService<ILogger<DivisionSheetService>>()) 
    );
}

I know my provider works because when I log things in a controller whose dependencies were injected from the HostBuilder's service collection (_sheetsClient), those messages work correctly. In classes that come from this other container (DivisionSheetService), those log messages go nowhere and when I view the ILogger instance in the debugger, it shows that it has no logger that it's writing to.

So it must be the case that my custom logging provider is unknown to the second container, but I can't figure out how to register it there.

Thanks in advance.

Upvotes: 1

Views: 2037

Answers (1)

M&#233;toule
M&#233;toule

Reputation: 14502

Since you're creating a new ServiceCollection from scratch, you also need to add the logging infrastructure from scratch:

IServiceCollection services = new ServiceCollection();
services.AddLogging(builder => builder.AddDebug().AddSignalRLogging());

Upvotes: 2

Related Questions