C#HostBuilder日志记录配置。非通用记录器为null

问题描述 投票:1回答:1

我安装了以下软件包的dotnet core 3控制台应用程序:

<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.1" />

这是我的全部最小的,可复制的完整程序:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace logging
{
    class Program
    {
        static void Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                })
                .Build();

            var logger = host.Services.GetService<ILogger>();
            var genericLogger = host.Services.GetService<ILogger<Program>>();
        }
    }
}

[当我尝试解析两个记录器时,可以解析一个通用记录器,但是非通用记录器始终为null。任何人都可以发现为什么我的非通用记录器为null吗?

c# logging .net-core
1个回答
0
投票

这是因为ILogger并未特别添加到服务集合中。仅通用

/// <summary>
/// Adds logging services to the specified <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="configure">The <see cref="ILoggingBuilder"/> configuration delegate.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddLogging(this IServiceCollection services, Action<ILoggingBuilder> configure)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.AddOptions();

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

    services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<LoggerFilterOptions>>(
        new DefaultLoggerLevelConfigureOptions(LogLevel.Information)));

    configure(new LoggingBuilder(services));
    return services;
}

Source

为了证明这一点,如果要使用您的示例来调用以下内容

var logger = host.Services.GetRequiredService<ILogger>();

它将抛出一个无法解析所提供类型的异常。

[ILogger通常不用于显式注入或解析,而是作为分配的基本类型

//...

private readonly ILogger logger;

public MyClass(ILogger<MyCLass> logger) {
    this.logger = logger;
}

//...
© www.soinside.com 2019 - 2024. All rights reserved.