Microsoft使用开放泛型类型和依赖注入进行日志记录

时间:2018-04-11 07:43:35

标签: c# logging dependency-injection

我真的试图围绕这一切。

我想使用开放泛型类型在我的“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);

但是,这完全违背了将记录器添加到我的服务的重点,或者我是不是我没有正确理解它?

1 个答案:

答案 0 :(得分:1)

看起来我忘了注册

services.AddLogging();