Search code examples
c#.netgrpc

gRPC with Legacy .NET Framework


Everything I've seen around gRPC seems to be in Dotnet Core.

I'm unfortunately constrained to using .NET Framework as I'm working on a legacy app.

I'd like to add some gRPC endpoints to it.

Can this be done in any reasonable way?


Solution

  • The Grpc.Core pacakage contains the (legacy) unmanaged client and server code and can be used on .NET Framework; typical usage would be:

    Server server = new Server
    {
        Ports = { new ServerPort("localhost", 10042, ServerCredentials.Insecure) },
        Services = {
            Calculator.BindService(calc),
            TimeService.BindService(clock),
        }
    };
    server.Start();
    Console.WriteLine("Server running... press any key");
    Console.ReadKey();
    await server.ShutdownAsync();
    

    A client would be more like:

    var channel = new Channel("localhost", 10042, ChannelCredentials.Insecure);
    try
    {
        var calc = new Calculator.CalculatorClient(channel);
        for (int i = 0; i < 5; i++)
        {
            using var ma = calc.MultiplyAsync(new MultiplyRequest { X = i, Y = i });
            var calcResult = await ma.ResponseAsync;
            Console.WriteLine(calcResult.Result);
        }
    
    
    
        var clock = new TimeService.TimeServiceClient(channel);
        using var subResult = clock.Subscribe(new Empty());
        var reader = subResult.ResponseStream;
        while (await reader.MoveNext(default))
        {
            var time = reader.Current.Time;
            Console.WriteLine($"The time is now {time}");
        }
    }
    finally
    {
        await channel.ShutdownAsync();
    }
    

    So: yes.