在 .NET 5.0 控制台应用程序中调用 ServiceProvider.GetRequiredService 时出现异常

Exception when calling ServiceProvider.GetRequiredService in a .NET 5.0 console app

我在我的 Program class 中拼凑了以下代码,几个小时后尝试查找有关 DI 的信息并登录 .NET 5.0 控制台应用程序。与网络应用程序上的信息相比,此类信息非常稀缺:

private static void BuildConfig(IConfigurationBuilder builder)
{
    builder.SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .AddEnvironmentVariables();
}

private static void ConfigureServices(ServiceCollection serviceCollection, ILogger logger)
{
    serviceCollection
        .AddLogging(builder => builder.AddSerilog(logger))
        .AddSingleton<ApplicationService>();
}

public static async Task<int> Main(string[] args)
{
    // Setup config
    var builder = new ConfigurationBuilder();
    BuildConfig(builder);

    // Setup logging
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Build())
        .CreateLogger();

    // Setup Dependency Injection         
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection, Log.Logger);
    var serviceProvider = serviceCollection.BuildServiceProvider();

    // Use dependency injection
    var applicationService = serviceProvider.GetRequiredService<ApplicationService>();

    var runResult = await applicationService.RunAsync(args);
    return runResult;
}

当我尝试 运行 我的应用程序时,出现以下错误:

System.InvalidOperationException: 'Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'DalBuilder.Lib.ApplicationService'.'

很可能在 ApplicationService 构造函数中使用了错误的记录器。

重构以使用内置记录器ILogger<ApplicationService>

//...

private readonly ILogger logger; //<-- use build-in logger

public ApplicationService(ILogger<ApplicationService> logger, ....) {

    this.logger = logger;

    //...
}

记录器的这个配置

//...

.AddLogging(builder => builder.AddSerilog(logger))

//...

基本上是将 Serilog 记录器包装在内置记录器中。