Is there a way of creating an instance of an object for each client in a gRPC Server?

652 Views Asked by At

I am creating a grpc client-server project. For every client I want to instatiate a different object:

My client class looks like:

static void Main(string[] args)
{
            Channel channel = new Channel("localhost", 5001,SslCredentials.Insecure);

            var client = new Greeter.GreeterClient(channel);
            var client2 = new Greeter.GreeterClient(channel);

            String user = "Alice";
            String user2 = "Bob";

            var reply = client.putName(new HelloRequest { Name = user });
            Console.WriteLine(reply.Message);
            var reply2 = client2.putName(new HelloRequest { Name = user2 });
            Console.WriteLine(reply2.Message);

            reply = client.getName();
            Console.WriteLine(reply.Message);
            reply2 = client2.getName();
            Console.WriteLine(reply2.Message);

            reply = client.modifyName(new HelloRequest { Name = "Frank" });
            Console.WriteLine(reply.Message);
            reply2 = client2.modifyName(new HelloRequest { Name = "Russel" });
            Console.WriteLine(reply2.Message);
}
public class GreeterService : Greeter.GreeterBase
{
    private IName n;
    private readonly ILogger<GreeterService> _logger;
    public GreeterService(ILogger<GreeterService> logger,IName n)
    {
        this.n = n;
        _logger = logger;
    }
    public override Task<HelloReply> putName(HelloRequest request, ServerCallContext context)
    {
        n.SetName(request.Name);
        return Task.FromResult(new HelloReply
            {
                Message = "User changed"
            });
    }

    public override Task<HelloReply> getName(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply
        {
            Message = this.name
        });
    }
    public override Task<HelloReply> modifyName(HelloRequest request, ServerCallContext context)
    {
        string new_name= n.SetName(request.Name);
        return Task.FromResult(new HelloReply
            {
                Message = "Hello " + new_name
            });
    }
}

I also added services.AddSingleton<IName>(new Name("name")); to the ConfigureServices method in Startup.cs.

The result of running my client is:

> User changed
> User changed
> Bob
> Bob
> Hello Frank
> Hello Russel

Instead, I want the server to keep an instance of each Name objects with the resulting output:

> User changed
> User changed
> Alice
> Bob
> Hello Frank
> Hello Russel

Is this possible using gRPC?

1

There are 1 best solutions below

0
On

for me it worked with:

builder.Services.AddSingleton<TYPEOFSERVICE>()

inside of the Startup or Program.cs

instead of

services.AddSingleton<IName>(new Name("name"))