Home > Software design >  Is it possible to add grpc services using different ports in Asp.Net Core grpc?
Is it possible to add grpc services using different ports in Asp.Net Core grpc?

Time:03-26

I have an existing .net core application that contains two grpc services (using grpc.core) . I have two servers

Server serverA = new Server(channelOptions)
            {
                Ports = { new ServerPort("0.0.0.0", 8090, credentials) },
            };
serverA.services.add(serviceA);
serverA.Start()

Server serverB = new Server(channelOptions)
            {
                Ports = { new ServerPort("0.0.0.0", 8091, credentials) },
            };
serverB.services.add(serviceB);
serverB.Start()

Now, I'm trying to migrate from grcp.core to asp.net core grpc, but I can not find a way to add two services with two different ports, when adding the services:

services.AddSingleton<ServiceA>();
services.AddSingleton<ServiceB>();

both are in the same port, Is there any way to set a port per service in asp.net core grpc ?

CodePudding user response:

From the 3.1 template project ASP.NET Core gRPC Service you can listen on two ports via launchsettings:

  "applicationUrl": "https://localhost:5001;https://localhost:5002",

And add branch routing based on port like this:

  app.UseRouting();
  app.MapWhen(context => context.Connection.LocalPort == 5001,
      iab => iab.UseRouting().UseEndpoints(endpoints => endpoints.MapGrpcService<GreeterService>()));
  app.MapWhen(context => context.Connection.LocalPort == 5002,
      iab => iab.UseRouting().UseEndpoints(endpoints => endpoints.MapGrpcService<GreeterServiceV2>()));
  • Related