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

如何在非托管控制台应用程序中实现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");
    }
}
评论
旗傲安
旗傲安

Add LogTest to the service collection and resolve it using the provider and the provider will inject the configured loggers

重构您的合成根

internal static class ContainerConfiguration {
    public static IServiceProvider Configure(Action<IServiceCollection> configuration = null) {
        var services = new ServiceCollection()
            .AddLogging(l => l.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();
}

如果使用提供程序,它将负责构建对象图,其中包括注入所需的依赖项。

点赞
评论