c# - 非托管 .NET 控制台中的依赖注入日志记录
问题描述
如何ILogger
在非托管控制台应用程序中实现依赖注入(如托管应用程序)?在下面的代码中,我想像logTest1
. 那可能吗?
下面是我的appsettings.json - 我宁愿不必定义每个类,但这无论如何都不起作用。
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"ClientTestCli.LogTest": "Trace"
}
}
我的控制台应用程序:
class Program
{
static void Main(string[] args)
{
HandleArgs(args);
var serviceProvider = ContainerConfiguration.Configure();
var logTest1 = new LogTest();
var logTest2 = new LogTest(serviceProvider.GetService<ILogger<LogTest>>());
logTest1.LogStuff();
logTest2.LogStuff();
}
}
容器配置:
internal static class ContainerConfiguration
{
public static ServiceProvider Configure()
{
return new ServiceCollection()
.AddLogging(l => l.AddConsole())
.Configure<LoggerFilterOptions>(c => c.MinLevel = LogLevel.Trace)
.BuildServiceProvider();
}
}
一个测试类:
internal class LogTest
{
ILogger<LogTest> logger;
public LogTest(ILogger<LogTest> logger = null)
{
this.logger = logger;
}
public void LogStuff()
{
logger?.LogCritical("This is a critical log");
}
}
解决方案
添加LogTest
到服务集合并使用提供者解决它,提供者将注入配置的记录器
重构你的组合根
internal static class ContainerConfiguration {
public static IServiceProvider Configure(Action<IServiceCollection> configuration = null) {
var services = new ServiceCollection()
.AddLogging(logging => {
logging.ClearProviders();
logging.AddConsole();
})
.Configure<LoggerFilterOptions>(c => c.MinLevel = LogLevel.Trace);
configuration?.Invoke(services);
return services.BuildServiceProvider();
}
}
并在启动时使用它
static void Main(string[] args) {
HandleArgs(args);
IServiceProvider serviceProvider = ContainerConfiguration.Configure(services => {
services.AddTransient<LogTest>();
});
LogTest logTest = serviceProvider.GetService<LogTest>();
logTest.LogStuff();
}
如果使用提供者,它将负责构建对象图,其中包括注入所需的依赖项。
.Net Fiddle一个工作示例。
推荐阅读
- ejabberd - 无法从非本地 ip 在 ejabberd 中注册
- java - SpringBootApplication在子包下找不到bean
- angular - 通过 Angular Renderer2 编辑画布不起作用
- android - 如何取消收集协程StateFlow?
- sql-server - SQL Server 通过分组数据使用多列排序顺序
- python - 为什么幻影js浏览器打不开?
- javascript - 收到新的 Google 表单提交后,如何忽略向具有价值的行发送电子邮件?
- python-3.x - 无法按指标过滤(comparisonValue 未在 400 值中重新识别
- javascript - 从 json 文件导入时,如何使我的 i18n-js 文本正确呈现?
- spring-boot - 即使在将成功的身份验证添加到 SecurityContextHolder 后也会出现 401 错误