ServiceModel.Grpc

Code-first for gRPC

View on GitHub

ServiceModel.Grpc server code generation

Reflection.Emit by default

By default all endpoints requested by gRPC service host are generating on demand via Reflection.Emit. Reflection.Emit endpoint class is generated only once for the specific service.

example AspNetCore hosting:

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            // under the hood:
            //   - generate gRPC endpoint class for MyService
            //   - bind the service
            endpoints.MapGrpcService<MyService>();
        });
    }
}

example Grpc.Core.Server hosting:

var server = new Grpc.Core.Server();

// under the hood:
//   - generate gRPC endpoint class for MyService
//   - bind the service
server.Services.AddServiceModelTransient(() => new MyService());

C# source code generator

To enable source code generation:

AspNetCore hosting:

[ExportGrpcService(typeof(MyService), GenerateAspNetExtensions = true)]
internal static partial class MyGrpcServices
{
    // generated code ...
    public static IServiceCollection AddMyServiceOptions(this IServiceCollection services, Action<ServiceModelGrpcServiceOptions<MyService>> configure) {}

    // generated code ...
    public static GrpcServiceEndpointConventionBuilder MapMyService(this IEndpointRouteBuilder builder) {}
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // optional configuration for MyService endpoint
        services.AddMyServiceOptions(options => { /*...*/ });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            // host MyService endpoint generated by ServiceModel.Grpc.DesignTime
            endpoints.MapMyService();
        });
    }
}

Grpc.Core.Server hosting:

[ExportGrpcService(typeof(MyService), GenerateSelfHostExtensions = true)]
internal static partial class MyGrpcServices
{
    // generated code ...
    public static Server.ServiceDefinitionCollection AddMyService(this Server.ServiceDefinitionCollection services, Func<MyService> serviceFactory, Action<ServiceModelGrpcServiceOptions> configure = default) {}

    // generated code ...
    public static Server.ServiceDefinitionCollection AddMyService(this Server.ServiceDefinitionCollection services, MyService service, Action<ServiceModelGrpcServiceOptions> configure = default) {}
}

var server = new Grpc.Core.Server();

// host MyService endpoint generated by ServiceModel.Grpc.DesignTime
server.Services.AddMyService(() => new MyService());