ASP Core在实用程序类中添加日志记录

问题描述

我们自动将记录器注入到通用控制器类中。但是,我们如何为通用实用程序类派生出与封闭控制器不同的通用类型的记录器呢?

public partial class GenericController<T> {
    public GenericController(ILogger<T> logger) 
    {  
          MyUtility<DifferentClass> utlDifferent = new MyUtility<DifferentClass>( /*????*/ );
          MyUtility<AnotherClass>   utlAnother   = new MyUtility<AnotherClass>( /*????*/ );
    }
}
...
public class MyUtility<P> {
    public MyUtility<P>(ILogger<P> logger) { }
}

有没有办法获取创建注入的记录器实例的LoggerFactory,并用它与所有相同的提供程序生成新的记录器?

解决方法

您需要MyUtility<P>,所以请注入它而不是ILogger<T>

public GenericController(MyUtility<DifferentClass> utlDifferent,MyUtility<AnotherClass> utlAnother)
{  
}

避免自己直接实例化对象(使用new ...)。让容器处理该问题,然后直接注入您所需的内容。

注意:如果MyUtility<P>实现了一个接口(例如IMyUtility<P>),那么会更容易-那么您可以使用开放的泛型将其添加到容器中:

services.AddScoped(typeof(IMyUtility<>),typeof(MyUtility<>));

那样,您可以改为注入接口:

public GenericController(IMyUtility<DifferentClass> utlDifferent,IMyUtility<AnotherClass> utlAnother)
{  
}

然后,通过模拟接口,您将更容易测试控制器。