gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:27 25 4
gpt4 key购买 nike

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

<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>>();
}
}
}

当我尝试解析这两个记录器时,通用的记录器可以正常解析,但非通用的记录器始终为空。谁能发现为什么我的非通用记录器为空?

最佳答案

是因为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 通常不用于显式注入(inject)或解析,而是作为赋值的基类型

例如

public class AboutModel : PageModel {
private readonly ILogger logger;

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

//...
}

或者在非主机控制台应用程序中

var loggerFactory = LoggerFactory.Create(builder => {
builder.AddConsole();
});

ILogger logger = loggerFactory.CreateLogger<Program>();

引用 Logging in .NET Core and ASP.NET Core

关于C# HostBuilder 日志记录配置。非通用记录器为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com