ASP 核心添加登录实用程序 类

ASP Core add logging in utility classes

我们自动将记录器注入通用控制器class。但是,我们如何为泛型实用程序 classes 派生一个记录器,这些泛型类型与封闭的 Controller 具有不同的泛型类型?

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)
{  
}

这样您就可以更轻松地测试您的控制器(通过模拟接口)。