【问题标题】:ASP Core add logging in utility classesASP Core 在实用程序类中添加日志记录
【发布时间】:2020-11-03 00:30:44
【问题描述】:

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

【问题讨论】:

    标签: asp.net-core ilogger iloggerfactory


    【解决方案1】:

    你需要MyUtility&lt;P&gt;,所以注入它而不是ILogger&lt;T&gt;

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

    避免自己直接实例化对象(使用new ...)。让容器来处理,直接注入你需要的东西。

    注意:如果MyUtility&lt;P&gt; 实现了一个接口(如IMyUtility&lt;P&gt;),这会更容易 - 然后你可以将它添加到具有开放泛型的容器中:

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

    这样你就可以注入接口了:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-04
      • 2023-04-08
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多