Search code examples
c#asp.net-core.net-corethrift

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


I wanted to know how to inject ILogger into a function in a ASP.NET Core app that's called by a Java client through Thrift.

So a high level code demo of what I want to do:

// 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;
    }
}

So I wanted to know how can I inject ILogger into TaskFunctions while calling from Thrift?


Solution

  • The accepted answer from this question on StackOverflow will help you.

    You need to build a ServiceCollection outside of the ASP.NET Core's Startup class.

    • the MVC part of your application will add those services in Startup.ConfigureServices method
    • the other part of your application will need to build and then use the service provider as such var taskFunctionsWithInjected = ActivatorUtilities.CreateInstance<TaskFunctions>(serviceProvider); in order to get the dependencies