GRPC service instantiated per call

Viewed 1801

I've created a GRPC service host under .NET core 3.1 (using Grpc.AspNetCore v2.30 from https://github.com/grpc/grpc-dotnet). By putting a breakpoint in the "ProxyService" constructor, I can see that the class is instantiated per call - every time a GRPC call is coming from a client, the breakpoint is hit. How do I configure it to always use the same ProxyService instance?

These are the program and Startup classes:

    class Program
    {
        const int _port = 23456;

        static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            Console.WriteLine("started - press any key to quit...");
            Console.ReadKey();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(options =>
                    {
                        options.ConfigureEndpointDefaults(o =>
                        {
                            o.Protocols = HttpProtocols.Http2;
                            
                        });
                        options.ListenAnyIP(_port);
                    });
                    webBuilder.UseStartup<Startup>();
                });
    }

    public class ProxyService : StreamingApi.Protos.StreamingApi.StreamingApiBase
    {
        public ProxyService()
        {
    // gets here with every client call
        }

        public override Task<UpdateResponse> Update(UpdateRequest request, ServerCallContext context)
        {
            return Task.FromResult(new UpdateResponse());
        }
    }

   class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<ProxyService>();
            });
        }
    }
2 Answers

First, let me guess why you want to do this:

  • You have some heavy-logic inside ProxyService like initialization of some sort;
  • You have static variables which you want to share between calls;

To resolve first case you should use either method itself:

    public ProxyService(IFooBar foobar)
    {
        this.foobar = foobar;
    }
    public override Task<UpdateResponse> Update(UpdateRequest request, ServerCallContext context)
    {
        await this.foobar.InitializeAsync();
        return Task.FromResult(new UpdateResponse());
    }

Or some other trigger in your system, like for example "At service start":

    public interface IFooBarInitilizer :IHostedService
    {
    }
    public class FooBarInitilizer : IFooBarInitilizer 
    {
        public async Task StartAsync(CancellationToken token){ await this.foobar.InitializeAsync(); }
    }

    //in your Configure
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
        services.AddSingleton<IFooBarInitializer, FooBarInitializer>();
        services.AddHostedService(x=> x.GetService<IFooBarInitializer>());
    }

For the second case it is even easier, because you just can specify your shared resources through interface dpendency:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddGrpc();
        services.AddSingleton<IFooBarResource, FooBarResource>();
    }

    
public class ProxyService : StreamingApi.Protos.StreamingApi.StreamingApiBase
{
    public ProxyService(IFooBarResource myStaticResource)
    {
        this.myStaticResource = myStaticResource;
    }

    public override Task<UpdateResponse> Update(UpdateRequest request, ServerCallContext context)
    {
        var somethingGood = this.myStaticResource.GetMeSomethingGood();
        return Task.FromResult(new UpdateResponse());
    }
}

According to this page you can register your grpc service yourself as a singleton.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
            services.AddSingleton(new ProxyService());
        }
Related