非托管DotNet控制台中的依赖项注入日志

问题描述 投票:1回答:1

如何在非托管控制台应用程序中实现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-core dependency-injection .net-core-logging
1个回答
0
投票

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的工作示例。

© www.soinside.com 2019 - 2024. All rights reserved.