解决方案 ILogger 不再默认注册,但 ILogger 是.如果您仍想使用 ILogger,您可以使用以下 (Startup.cs) 手动注册: public void ConfigureServices(IServiceCollection services){var serviceProvider = services.BuildServiceProvider();var logger = serviceProvider.GetService>();services.AddSingleton(typeof(ILogger), logger);...}其中 AnyClass 可以是通用的,例如: 公共类 ApplicationLogs{}所以: public void ConfigureServices(IServiceCollection services){var serviceProvider = services.BuildServiceProvider();var logger = serviceProvider.GetService>();services.AddSingleton(typeof(ILogger), logger);...}ILogger 现在将通过构造函数注入解析I've configured my console application's Main like sovar services = new ServiceCollection() .AddLogging(logging => logging.AddConsole()) .BuildServiceProvider();And then I try to use it in another class like so private readonly ILogger _logger; public MyClass(ILogger logger) { _logger = logger; } public void MyFunc() { _logger.Log(LogLevel.Error, "My Message"); }I've tried the solutions here but it didn't work for me.EditBased on Yaakov's comment below and this Github comment I'm able to resolve it correctly by doing this public MyClass(ILogger<MyClass> logger) { _logger = logger; }I would have preferred to have this in the initial BuildServiceProvider but looks like I'm gonna have to repeat this every time I want to use the logger (or create my own ILogger). 解决方案 ILogger is no longer registered by default but ILogger<T> is. If you still want to use ILogger you can registered it manually with the following (Startup.cs): public void ConfigureServices(IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetService<ILogger<AnyClass>>(); services.AddSingleton(typeof(ILogger), logger); ... }Where AnyClass can be something generic, such as: public class ApplicationLogs { }So: public void ConfigureServices(IServiceCollection services) { var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetService<ILogger<ApplicationLog>>(); services.AddSingleton(typeof(ILogger), logger); ... }ILogger will now resolve via constructor injection 这篇关于无法从 Microsoft.Extensions.Logging 解析 ILogger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-04 08:07