'How can I get the registered service with the gRPC service class or function instead of in the Main() function
I have a gRPC service with several functions.
To make it simple
public GreeterService : GreeterServiceBase
{
public override Task<SayHelloResponse> SayHello(SayHelloRequest request, ServerCallContext context) {...}
public override Task<SayByeResponse> SayBye(SayByeRequest request, ServerCallContext context) {...}
}
After I registered the dependency in Startup.ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddGrpc();
services.AddSingleton<IMyInterface, IMyInterfaceImpl>();
}
According to the page https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1,
I can get it back at Program.Main() through serviceScope.ServiceProvider
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var myDependency = services.GetRequiredService<IMyDependency>();
myDependency.WriteMessage("Call services from main");
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred.");
}
}
host.Run();
}
}
One point I am not quite sure is how can I get it at my gRPC service (GreeterService) or functions (SayHello() and SayBye()), it looks like that I cannot get the Services via ServerCallContext.
Any help is highly appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
