gpt4 book ai didi

c# - LoggerFactory 生成 InvalidOperationException

转载 作者:行者123 更新时间:2023-12-01 17:50:20 28 4
gpt4 key购买 nike

我使用 Microsoft.Extensions.Logging 创建了一个使用服务层的控制台应用程序。

Program.cs

public static void Main(string[] args)
{
// Create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);

// Create service provider
var serviceProvider = serviceCollection.BuildServiceProvider();

// Entry to run app
serviceProvider.GetService<App>().Run().RunSynchronously();
}

private static void ConfigureServices(IServiceCollection serviceCollection)
{
// Configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.Build();

serviceCollection.AddOptions();
serviceCollection.Configure<Settings>(options =>
{
//...
});

// Services
serviceCollection.AddTransient<IOneService, OneService>();
serviceCollection.AddTransient<ISecondService, SecondService>();

// Repositories
serviceCollection.AddTransient<MyContext, MyContext>();
serviceCollection.AddTransient<IOneRepository, OneRepository>();

// App
serviceCollection.AddTransient<App>();

// Logger

// Automapper
serviceCollection.AddSingleton(new AutoMapperProfileConfiguration());
serviceCollection.AddScoped<IMapper>(sp =>
new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
}

我收到此错误

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1

我猜我必须为 .NET Core 日志设置 LoggerFactory 和 Microsoft.Extensions.Logging,但我无法正确设置。

我在 Main() 中尝试过类似的方法:

// Attempt 1
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole()
.AddDebug();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
"This is a test of the emergency broadcast system.");

// Attempt 2
serviceCollection.AddSingleton(new LoggerFactory()
.AddConsole()
.AddDebug());

有什么想法吗?

最佳答案

它应该有效:

var serviceProvider = new ServiceCollection()
.AddLogging() //<-- You were missing this
.BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();

要安装的软件包:Microsoft.Extensions.DependencyInjection;Microsoft.Extensions.Logging;

关于c# - LoggerFactory 生成 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295248/

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