简体   繁体   中英

Task parameter scope on gRPC server

I have a gRPC server Task that gets called from clients. The request parameter is scoped in the Task and i dont know how to retrieve it and use it in other classes. printing "currentRequest" outside of the task returns nothing. Thank you so much for your help.

public class LoggingImpl : Logging.LoggingBase
{
    private Server server;
    RequestInfo currentRequest;
    public ClientController controller;

    public override Task<LoggingResponse> LoggingMCM(RequestInfo request, ServerCallContext context)
    {
        currentRequest = request;
        Console.Log(currentRequest);
        return Task.FromResult(new LoggingResponse { Result = "this is a reply from Unity Server" });
    }

    public void GetRequestInfo()
    {
        Console.Log(currentRequest);
    }


    public void StartServer()
    {
        server = new Server
        {
            Services = { Logging.BindService(new LoggingImpl()) },
            Ports = { new ServerPort("127.0.0.1", 50010, ServerCredentials.Insecure) }

        };
        server.Start();
    }
}

I was expecting the currentRequest to be usable outside of the Taks scope. How would one use the request info on the main thread and other classes?

Since gRPC services are registered as transient (at least if they are registered the standard way), a new instance of your class LogginImpl will be created for each gRPC call to the service.

Making the request static could result in the behaviour you expect, since it will not be re-instantiated with each call (in line 4):

private static RequestInfo currentRequest;

Keep in mind, if you want log a (string) message from the request, you still have to extract the message from the request (since you pass the whole object to the Console in the GetRequestInfo() method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM