我正在尝试使用.NET CORE 3.1构建控制台应用程序,但在注入控制台记录器时遇到了问题。
最近几个版本中注入日志的方式似乎已经发生了显著变化,各种不同风味的教程似乎都不能匹配我所要做的事情。
我有一个接口:
public interface IMyDoer
{
void DoSomething();
}
我想往一个类中注入ILogger:
public class MyDoer : IMyDoer
{
private readonly ILogger logger;
public MyDoer(ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
this.logger.Log(LogLevel.Information, "Doing something");
}
}
然后我有我的Main()函数,在这里我试图配置一个DI容器来构造一个Doer对象,并将ILogger配置为记录到控制台。
public class Program
{
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
var serviceProvider serviceCollection.BuildServiceProvider();
var myDoer = serviceProvider.GetService<IMyDoer>();
myDoer.DoSomething();
}
private static void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection.AddLogging(configure => {
configure.AddConsole();
});
serviceCollection.AddSingleton<IMyDoer, MyDoer>();
}
}
作为另一种选择,我尝试过以下方法:
public class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
using (var serviceProvider = serviceCollection.BuildServiceProvider())
using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
{
var myDoer = serviceProvider.GetService<IMyDoer>();
myDoer.DoSomething();
}
}
private static void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection
.AddSingleton<IMyDoer, MyDoer>();
}
}
无论哪种情况,我都会收到一个异常:
System.InvalidOperationException
HResult=0x80131509
Message=Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyDoer.DoSomething'.
Source=Microsoft.Extensions.DependencyInjection
有什么建议可以告诉我该怎么做吗?