首页 > 解决方案 > 非托管 .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");
    }
}

标签: c#logging.net-coredependency-injection.net-core-logging

解决方案


添加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一个工作示例。


推荐阅读