将 ILogger 注入到 .NET Core 3 中 Thrift 调用的函数中

Injecting ILogger into a function called by Thrift in .NET Core 3

我想知道如何将 ILogger 注入 ASP.NET 核心应用程序中的函数,该应用程序由 Java 客户端通过 Thrift 调用。

我想做的高级代码演示:

// ExecuteRequest is called by java client through Thrift
public class ThriftLayer
{
    ...
    public string ExecuteRequest(...params)
    {
        ...
        var result = RequestFunc1(...params);
        ...do processing
        return result;
    }
    ...
}
// Contains request functions called by ExecuteRequest
public class ServerRequestHandler
{
    ...
    public string RequestFunc1(...params)
    {
       return TaskFunc1(...params);
    }
    ....
}
// Functions in this class are called by both the Thrift layer(called by ServerRequestHandler) as well as a Console application
// In Console applications, we can inject the ILogger at Startup - No issues there. 
public class TaskFunctions
{
    private readonly ILogger<TaskFunctions> _logger;

    public TaskFunctions(ILogger<TaskFunctions> logger)
    {
        _logger = logger;
    }

    public string TaskFunc1(...params)
    {
       _logger.logInfo("<log message>");
       ...do processing
       return stringResult;
    }
}

所以我想知道如何在从 Thrift 调用时将 ILogger 注入到 TaskFunctions 中?

Whosebug 上的这个问题

会对你有所帮助。

您需要在 ASP.NET 核心 Startup class.

之外构建一个 ServiceCollection
  • 您的应用程序的 MVC 部分将在 Startup.ConfigureServices 方法中添加这些服务
  • 您的应用程序的另一部分将需要构建然后使用服务提供者 var taskFunctionsWithInjected = ActivatorUtilities.CreateInstance<TaskFunctions>(serviceProvider); 以获得依赖项