【问题标题】:Injecting ILogger into a function called by Thrift in .NET Core 3将 ILogger 注入到 .NET Core 3 中 Thrift 调用的函数中
【发布时间】:2020-05-18 23:22:07
【问题描述】:

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

所以我想做一个高级代码演示:

// 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?

【问题讨论】:

    标签: c# asp.net-core .net-core thrift


    【解决方案1】:

    The accepted answer 来自 StackOverflow 上的这个问题会帮助你。

    您需要在 ASP.NET Core 的 Startup 类之外构建一个 ServiceCollection

    • 应用程序的 MVC 部分将在 Startup.ConfigureServices 方法中添加这些服务
    • 您的应用程序的其他部分需要构建然后使用服务提供者 var taskFunctionsWithInjected = ActivatorUtilities.CreateInstance&lt;TaskFunctions&gt;(serviceProvider); 以获取依赖项

    【讨论】:

    • 我明白了。非常感谢您的回答
    猜你喜欢
    • 2022-08-22
    • 2018-08-08
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2021-12-17
    相关资源
    最近更新 更多