0

我们自动将记录器注入到通用控制器类中。但是我们如何为泛型实用程序类派生一个记录器,该类的泛型类型与封闭的 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 并使用它来生成具有所有相同提供程序的新记录器?

4

1 回答 1

0

你需要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)
{  
}

然后你会更容易测试你的控制器(通过模拟接口)。

于 2020-11-03T01:15:53.673 回答