【问题标题】:Microsoft Logging with open generic types and Dependency Injection具有开放泛型类型和依赖注入的 Microsoft Logging
【发布时间】:2018-04-11 07:43:34
【问题描述】:

我真的很想把所有这些都包起来。

我想在使用开放泛型类型的“AddTextCalculator1”示例类中使用 ILogger。

As noted here

首先我注册服务

var serviceProvider = new ServiceCollection()
    .AddLogging()
    .BuildServiceProvider();

var logger = serviceProvider.GetService<ILoggerFactory>()
    .CreateLogger<Program>();

var services = new ServiceCollection();
services.AddInternalServices();
services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));
services.AddTextCalculator1();

var testCalculatorOneService = provider.GetService<ISomeCalculationOne>();

然后是 IServiceCollectionExtension 类

public static class IServiceCollectionExtension
{
    public static IServiceCollection AddTextCalculator1(this IServiceCollection services )
    {
        //services.AddTransient<ISomeCalculationOne>(s => new SomeCalculationOne(serviceProvider));
        services.AddTransient<ISomeCalculationOne, SomeCalculationOne>();
        return services;
    }
}

我的界面

public interface ISomeCalculationOne 
{
    void DoSomeCalcAndOutputToScreen();
}

然后是我的课

public class SomeCalculationOne : ISomeCalculationOne
{
    public ILogger _logger { get; private set; }

    public SomeCalculationOne(ILogger<SomeCalculationOne> logger)
    {
        _logger = logger;
        _logger.LogInformation("Constructed - HOT DAIMN!!!!");
    }

    public void DoSomeCalcAndOutputToScreen()
    {
        int a = 1 + 1;
        _logger.LogDebug("This is a debug logging test");
        Console.WriteLine(a.ToString());
    }
}

它当前抛出一个错误,因为我没有将 ILogger 类型的记录器传递给我的构造函数(请注意我的 IServiceCollectionExtension 类中注释掉的代码)

System.InvalidOperationException: '无法解析服务类型 'Microsoft.Extensions.Logging.ILoggerFactory' 尝试 激活'Microsoft.Extensions.Logging.Logger`

但这意味着我在定义我的服务时必须传入 ILogger 类型的记录器

services.AddTextCalculator1(ILogger<SomeCalculationOne> bla);

但这完全违背了首先将记录器添加到我的服务的意义,或者我没有正确理解它?

【问题讨论】:

  • 您还没有注册 ILoggerFactory 的实例,我猜它是具体 impl Logger 的必需依赖项。实际的开放通用注册对我来说看起来不错。
  • SomeCalculationOne CTOR 将抛出一个 NRE。 _logger 永远不会设置为 logger,但 a 是。尝试在 _logger 上调用 LogInformation 时,它将为空。旁注:为什么 _logger 是公开的?
  • @Fildor 啊,那是我错误地将其复制到stackoverflow。更新了我现在的样子。谢谢
  • @Mardoxx 为什么我需要 ILoggerFactory?在这种情况下,工厂的目的是什么?
  • @Mardoxx 好像忘记注册 services.AddLogging();

标签: c# logging dependency-injection


【解决方案1】:

好像忘记注册了

services.AddLogging();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多