【问题标题】:How to use ILogger in DomainObjects?如何在 DomainObjects 中使用 ILogger?
【发布时间】:2020-10-09 14:56:17
【问题描述】:

我有一个带有 FunctionRuntime v3 和依赖注入的 Azure Function App。

通常我使用

注入记录器
public TestRepositoryy(ILoggerFactory loggerFactory)
{
     _tenantBasedDocumentClient = tenantBasedDocumentClient;
     _log = loggerFactory.CreateLogger(GetType().Namespace);
}
     

如何将 ILogger 注入到域对象之类的东西中,其中对象不是通过 Startup-Configuration 创建的

【问题讨论】:

    标签: azure logging azure-functions


    【解决方案1】:

    虽然建议使用依赖注入,您只需在构造函数中声明ILogger<TestRepository>,函数运行时将自动解析记录器。

    public TestRepositoryy(ILogger<TestRepository> logger)
    {
         _log = logger;
    }
    

    但由于您提到您不是通过 DI 创建域对象,因此您可以在创建对象时从调用函数传递 ILogger 实例。

    public TestRepository(ILogger logger)
    {
         _log = logger;
    }
    
    // below is the Function entry point where ILogger is automatically injected.
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger logger)
    {
        var myRepository = TestRepository(logger);
        // blah blah
    }
    

    在函数here中阅读更多关于ILogger的信息

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2017-09-11
      • 2017-03-11
      • 1970-01-01
      相关资源
      最近更新 更多