Dotnetifying gRPC

By João Antunes

- 18 minutes read - 3713 words
C# + gRPC

I started this little proof of concept with the simple goal of creating some helper functions to aid in hosting gRPC services in .NET in a way similar to ASP.NET applications. However, while scouring the web, reading some articles to try and find the best way to do that, I came across this article and realized I could get a little more creative - maybe I ended up being too much, but at least I had fun along the way :).

I’ll try to cover the main bits of what I’ve done here, but if something you find important to get the whole picture that isn’t here, please tell me and I’ll try to improve the explanation.

You can follow along the code that’s on GitHub (I created a tag to make it easy to relate this article to the code).

Grab some popcorn, this is a looooong post!

What’s this “dotnetifying”?

So, like I said the initial goal was just to make the service hosting somewhat similar to an ASP.NET application. Besides hosting, if the service client registration could also be streamlined, that would also be great (and probably the easiest part before I started to get too creative).

These were the initial goals. What I started to wonder after reading the aforementioned article, was that I could probably make the service implementation experience different as well, taking inspiration from Entity Framework Code First, that is, instead of the usual code generation that’s required when using gRPC, one could just create the service interface, the messages to use as requests and responses, create the service implementation and using it all without even touching a .proto file and the other usual tools - as long as you don’t need to interop with other languages, in that case you better write that .proto file so the others can generate their stuff.

What I’m not trying to do

With this PoC I’m not trying to abstract away the core gRPC libraries, I’m using them and exposing them as needed. So even if using this code to simplify the development of these services, knowledge of the underlying core libraries is needed.

The usual way

Before talking about what I wanted to achieve, it might be better to start with a quick intro on creating a very simple service with gRPC the normal way.

We start by creating a .proto file containing the service description.

 1syntax = "proto3";
 3option csharp_namespace = "CodingMilitia.Grpc.GeneratedServerInterop.Generated";
 5service SampleService {
 6    rpc Send(SampleRequest) returns (SampleResponse) {}
 9message SampleRequest {
10    int32 value = 1;
13message SampleResponse {
14    int32 value = 1;

Then we use the tools that are installed with the Grpc.Tools NuGet package to generate the C# code.

1./protoc service.proto --csharp_out ./Generated/. --grpc_out ./Generated/. --plugin=protoc-gen-grpc=grpc_csharp_plugin

With the generated code we can use the generated client (class SampleServiceClient) to invoke an already running service or inherit from the generated service base (class SampleServiceBase) to implement the server side.

2 var server = new Server
4    Services = { Generated.SampleService.BindService(new SampleServiceImplementation()) },
5    Ports = { new ServerPort("", 5000, ServerCredentials.Insecure) }
2var channel = new Channel("", ChannelCredentials.Insecure);
3var client = new Generated.SampleService.SampleServiceClient(channel);
4var request = new Generated.SampleRequest { Value = 1 };
5var response = await client.SendAsync(request);

Like I said at the beginning, my initial goal was just to wrap this with some helper methods for DI and simplify hosting, but then, I went rogue…

Desired outcome

Just to provide a glimpse of the desired outcome in terms of hosting and consuming the services, here’s a bit of wishful thinking code (that actually works).

Shared between client and server

 2public interface ISampleService : IGrpcService
 4    [GrpcMethod("Send")]
 5    Task<SampleResponse> SendAsync(SampleRequest request, CancellationToken ct);
 9public class SampleRequest
11    [ProtoBuf.ProtoMember(1)]
12    public int Value { get; set; }
16public class SampleResponse
18    [ProtoBuf.ProtoMember(1)]
19    public int Value { get; set; }

The attributes above the messages are dependant on the serializer used. I’m using protobuf-net to implement the serializer, hence the attributes used.


1var serverHostBuilder = new HostBuilder()
2    .ConfigureServices((hostContext, services) =>
3    {
4        services.AddGrpcServer<ISampleService, SampleService>(new GrpcServerOptions { Url = "", Port = 5000 });
5    });
7await serverHostBuilder.RunConsoleAsync(cts.Token);


1//in a normal scenario we wouldn't instantiate the ServiceCollection, it's just for demo purposes
2var clientServices = new ServiceCollection()
3    .AddGrpcClient<ISampleService>(new GrpcClientOptions { Url = "", Port = 5000 })
4    .BuildServiceProvider();
5var client = clientServices.GetRequiredService<ISampleService>();
6var request = new SampleRequest { Value = 1 };
7var response = await client.SendAsync(request, CancellationToken.None);

Implementing it

So, like I said previously, the inspiration to what I ended up with came from the article by Horusiath. In a nutshell, he takes advantage of the core gRPC libraries classes that are used by the generated code to create the service and client classes without any code generation - plus, he uses a custom Protocol Buffers serializer, as opposed to the also usually generated ones.

The base for it all

So, to start with the things that are common to both client and server.

A gRPC service is composed of methods. There are 4 types of methods: unary, server streaming, client streaming and duplex streaming - for this PoC I implemented just the most basic type, unary, a simple request response.

To create the method definitions, I built an helper class MethodDefinitionGenerator (my naming skills are a bit weak, sorry about that) that exposes a method CreateMethodDefinition, that returns a Method<TRequest, TResponse> - this class is part of the core gRPC library. For each service method it’s required a method type (that right now will always be Unary), the service and method names, as well as a serializer for the messages. The serializer is configurable because I’m using a third party library to implement it, so I thought it was best to keep it easy to change.

 1using System;
 2using CodingMilitia.Grpc.Serializers;
 3using Grpc.Core;
 5namespace CodingMilitia.Grpc.Shared.Internal
 7    //TODO: review visibility
 8    public static class MethodDefinitionGenerator
 9    {
10        public static Method<TRequest, TResponse> CreateMethodDefinition<TRequest, TResponse>(
11            MethodType methodType,
12            string serviceName,
13            string methodName,
14            ISerializer serializer
15        )
16            where TRequest : class
17            where TResponse : class
18        {
19            return new Method<TRequest, TResponse>(
20                type: methodType,
21                serviceName: serviceName,
22                name: methodName,
23                requestMarshaller: Marshallers.Create(
24                    serializer: serializer.ToBytes<TRequest>,
25                    deserializer: serializer.FromBytes<TRequest>
26                ),
27                responseMarshaller: Marshallers.Create(
28                    serializer: serializer.ToBytes<TResponse>,
29                    deserializer: serializer.FromBytes<TResponse>
30                )
31            );
32        }
33    }

The ISerializer interface is the simplest thing ever (but after reading this article I might change the approach). It just exposes a couple of methods to serialize and deserialize a generic type T to and from a byte[].

1namespace CodingMilitia.Grpc.Serializers
3    public interface ISerializer
4    {
5         byte[] ToBytes<T>(T input);
6         T FromBytes<T>(byte[] input);
7    }

Besides these, there’s also a couple of attributes to apply to the service interface and methods, right now only to configure the names that’ll be used in the method definitions.

 1using System;
 3namespace CodingMilitia.Grpc.Shared.Attributes
 5    [AttributeUsage(AttributeTargets.Interface)] 
 6    public class GrpcServiceAttribute : Attribute
 7    {
 8        public string Name { get; set; }
10        public GrpcServiceAttribute(string name)
11        {
12            Name = name;
13        }
14    }
 1using System;
 3namespace CodingMilitia.Grpc.Shared.Attributes
 5    [AttributeUsage(AttributeTargets.Method)] 
 6    public class GrpcMethodAttribute : Attribute
 7    {
 8        public string Name { get; set; }
10        public GrpcMethodAttribute(string name)
11        {
12            Name = name;
13        }
14    }


For the server side, I initially thought I had to implement some hosting helpers to have the service hosted in a console application in a similar way to ASP.NET Core. Then I realised this was already done in .NET Core 2.1 (that is in preview 1 at this point), which would avoid a good amount of work. So, leveraging the new hosting options, the very simple class GrpcBackgroundService implements IHostedService, and simply starts and stops a GrpcHost instance. Right now GrpcHost, is a thin abstraction on the core gRPC libraries’ Server class that handles the hosting of the services.

 1using CodingMilitia.Grpc.Shared;
 2using Microsoft.Extensions.Hosting;
 3using System.Threading;
 4using System.Threading.Tasks;
 6namespace CodingMilitia.Grpc.Server.Internal
 8    internal class GrpcBackgroundService<TService> : IHostedService where TService : class, IGrpcService
 9    {
10        private readonly GrpcHost<TService> _host;
12        public GrpcBackgroundService(GrpcHost<TService> host)
13        {
14            _host = host;
15        }
17        public async Task StartAsync(CancellationToken cancellationToken)
18        {
19            await _host.StartAsync().ConfigureAwait(false);
20        }
22        public async Task StopAsync(CancellationToken cancellationToken)
23        {
24            await _host.StopAsync().ConfigureAwait(false);
25        }
26    }
 1using CodingMilitia.Grpc.Shared;
 2using System.Threading.Tasks;
 3using GrpcCore = Grpc.Core;
 5namespace CodingMilitia.Grpc.Server.Internal
 7    internal class GrpcHost<TService> where TService : class, IGrpcService
 8    {
 9        private readonly GrpcCore.Server _server;
11        public GrpcHost(GrpcCore.Server server)
12        {
13            _server = server;
14        }
16        public Task StartAsync()
17        {
18            _server.Start();
19            return Task.CompletedTask;
20        }
22        public async Task StopAsync()
23        {
24            await _server.ShutdownAsync().ConfigureAwait(false);
25        }
26    }

To get the simple service implementation registration with DI we saw before on the “desired outcome” part, there’s an extension method on IServiceCollection that registers GrpcBackgroundService and the GrpcHost as singletons, as well as the provided service implementation as scoped, to achieve an ASP.NET MVC controller like behavior - one instance per request.

 1using CodingMilitia.Grpc.Serializers;
 2using CodingMilitia.Grpc.Server.Internal;
 3using CodingMilitia.Grpc.Shared;
 4using Microsoft.Extensions.DependencyInjection;
 5using Microsoft.Extensions.Hosting;
 7namespace CodingMilitia.Grpc.Server
 9    public static class ServiceCollectionExtensions
10    {
11        public static IServiceCollection AddGrpcServer<TServiceInterface, TServiceImplementation>(
12            this IServiceCollection serviceCollection,
13            GrpcServerOptions options,
14            ISerializer serializer
15        )
16            where TServiceInterface : class, IGrpcService
17            where TServiceImplementation : class, IGrpcService, TServiceInterface
18        {
19            serviceCollection.AddScoped<TServiceInterface, TServiceImplementation>();
20            serviceCollection.AddSingleton<GrpcHost<TServiceInterface>>(
21                appServices => GrpcHostFactory.Create<TServiceInterface>(appServices, options, serializer)
22            );
24            serviceCollection.AddSingleton<IHostedService, GrpcBackgroundService<TServiceInterface>>();
25            return serviceCollection;
26        }
27    }

As can be seen above, besides what was already mentioned, there is also a call to a GrpcHostFactory.Create that’s responsible for creating the required GrpcHost, and here is where most of the code first magic for the server lives.

 1using CodingMilitia.Grpc.Serializers;
 2using CodingMilitia.Grpc.Shared;
 3using CodingMilitia.Grpc.Shared.Attributes;
 4using System;
 5using System.Reflection;
 7namespace CodingMilitia.Grpc.Server.Internal
 9    internal static class GrpcHostFactory
10    {
11        public static GrpcHost<TService> Create<TService>(
12            IServiceProvider appServices,
13            GrpcServerOptions options,
14            ISerializer serializer
15        )
16            where TService : class, IGrpcService
17        {
18            var builder = new GrpcHostBuilder<TService>(appServices);
19            builder.SetOptions(options);
20            builder.SetSerializer(serializer);
21            builder.AddUnaryMethods();
22            return builder.Build();
23        }
25        private static GrpcHostBuilder<TService> AddUnaryMethods<TService>(
26            this GrpcHostBuilder<TService> builder
27        )
28            where TService : class, IGrpcService
29        {
30            //TODO: right now it goes through every method, these must be validated and filtered
31            var serviceType = typeof(TService);
32            var serviceName = ((GrpcServiceAttribute)serviceType.GetCustomAttribute(typeof(GrpcServiceAttribute))).Name ?? serviceType.Name;
34            foreach (var method in serviceType.GetMethods())
35            {
36                var requestType = method.GetParameters()[0].ParameterType;
37                var responseType = method.ReturnType.GenericTypeArguments[0];
39                var handlerGenerator = typeof(MethodHandlerGenerator).GetMethod(nameof(MethodHandlerGenerator.GenerateUnaryMethodHandler));
40                handlerGenerator = handlerGenerator.MakeGenericMethod(serviceType, requestType, responseType);
41                var handler = handlerGenerator.Invoke(null, new[] { method });
43                var addUnaryMethod = typeof(GrpcHostBuilder<TService>).GetMethod(nameof(GrpcHostBuilder<TService>.AddUnaryMethod), BindingFlags.Public | BindingFlags.Instance);
44                addUnaryMethod = addUnaryMethod.MakeGenericMethod(requestType, responseType);
46                var methodName = ((GrpcMethodAttribute)method.GetCustomAttribute(typeof(GrpcMethodAttribute))).Name ?? method.Name;
48                addUnaryMethod.Invoke(builder, new[] { handler, serviceName, methodName });
49            }
51            return builder;
52        }
53    }

As you can see, this is where the shenanigans start - not that it’s super hard, but a bit trickier than usual, mainly because we get into reflection land. The beginning is straightforward, setting the options and the serializer on a GrpcHostBuilder instance. After that it starts iterating on all of the service interface methods, assuming they’re all unary methods and performing no validation whatsoever (yes, this really needs to be improved).

For each method, it creates an handler using the MethodHandlerGenerator class. The handler is basically a Func that wraps a call to the service implementation method, using an instance provided to it. The obtained handler is then passed along as an argument to the AddUnaryMethod method of the builder.

The GrpcHostBuilder works with the core gRPC libraries’ ServerServiceDefinition.Builder to create the Server.

 1using CodingMilitia.Grpc.Serializers;
 2using CodingMilitia.Grpc.Shared;
 3using CodingMilitia.Grpc.Shared.Internal;
 4using Grpc.Core;
 5using Microsoft.Extensions.DependencyInjection;
 6using System;
 7using System.Threading;
 8using System.Threading.Tasks;
10namespace CodingMilitia.Grpc.Server.Internal
12    internal class GrpcHostBuilder<TService> where TService : class, IGrpcService
13    {
14        private readonly IServiceProvider _appServices;
15        private readonly ServerServiceDefinition.Builder _builder;
16        private GrpcServerOptions _options;
17        private ISerializer _serializer;
19        public GrpcHostBuilder(IServiceProvider appServices)
20        {
21            _appServices = appServices;
22            _builder = ServerServiceDefinition.CreateBuilder();
23        }
25        public GrpcHostBuilder<TService> SetOptions(GrpcServerOptions options)
26        {
27            _options = options;
28            return this;
29        }
31        public GrpcHostBuilder<TService> SetSerializer(ISerializer serializer)
32        {
33            _serializer = serializer;
34            return this;
35        }
37        public GrpcHost<TService> Build()
38        {
39            var server = new global::Grpc.Core.Server
40            {
41                Ports = { { _options.Url, _options.Port, ServerCredentials.Insecure } },
42                Services =
43                {
44                    _builder.Build()
45                }
46            };
47            return new GrpcHost<TService>(server);
48        }
50        public GrpcHostBuilder<TService> AddUnaryMethod<TRequest, TResponse>(
51            Func<TService, TRequest, CancellationToken, Task<TResponse>> handler,
52            string serviceName,
53            string methodName
54        )
55            where TRequest : class
56            where TResponse : class
57        {
58            _builder.AddMethod(
59                MethodDefinitionGenerator.CreateMethodDefinition<TRequest, TResponse>(MethodType.Unary, serviceName, methodName, _serializer),
60                async (request, context) =>
61                {
62                    using (var scope = _appServices.CreateScope())
63                    {
64                        var service = scope.ServiceProvider.GetRequiredService<TService>();
65                        var baseService = service as GrpcServiceBase;
66                        if (baseService != null)
67                        {
68                            baseService.Context = context;
69                        }
70                        return await handler(service, request, context.CancellationToken).ConfigureAwait(false);
71                    }
72                }
73            );
74            return this;
75        }
76    }

In the builder constructor we get an IServiceProvider so we can fetch a service implementation per request. The SetOptions and SetSerializer methods are pretty self-explanatory, as is the Build method, that basically just creates the final Server instance using the provided arguments and the ServerServiceDefinition.Builder end product.

The AddUnaryMethod method calls the inner builder AddMethod, providing the method definition (created with the previously discussed MethodDefinitionGenerator) and a lambda to handle the requests. The lambda creates a new scope with the IServiceProvider, fetches a new service instance and uses the handler to invoke the desired method. If the service extends GrpcServiceBase, the ServiceCallContext is set, much like the HttpContext on an MVC Controller class.

Still with me this far? Nice! Onwards to the client side of things and some added craziness.


On the client side of things, we basically need to generate a proxy class, somewhat like the generated SOAP service we have in WCF. The development time generation is basically what gRPC’s tooling does, but as I’m being a smartass, I’m doing it at runtime (because, you know, reasons).

This is definitely the most overengineered part of this PoC, but at least I got to play around with something I hadn’t before - IL emitting!

Like for the server stuff, let me start the story from the outside and gradually dig into the more obscure stuff.

Just like the server side of things, I created an extension method over IServiceCollection to register the client as a singleton. The client is obtained with a call to GrpcClientFactory.Create.

 1using CodingMilitia.Grpc.Serializers;
 2using CodingMilitia.Grpc.Shared;
 3using Microsoft.Extensions.DependencyInjection;
 5namespace CodingMilitia.Grpc.Client
 7    public static class ServiceCollectionExtensions
 8    {
 9        public static IServiceCollection AddGrpcClient<TServiceInterface>(
10            this IServiceCollection serviceCollection,
11            GrpcClientOptions options,
12            ISerializer serializer
13        )
14            where TServiceInterface : class, IGrpcService
15        {
16            serviceCollection.AddSingleton<TServiceInterface>(_ => GrpcClientFactory.Create<TServiceInterface>(options, serializer));
17            return serviceCollection;
18        }
19    }

The factory just uses the GrpcClientTypeBuilder class to create the client proxy type and then returns a new instance of it.

 1using System;
 2using System.Linq;
 3using System.Reflection;
 4using System.Reflection.Emit;
 5using CodingMilitia.Grpc.Serializers;
 6using CodingMilitia.Grpc.Shared;
 7using CodingMilitia.Grpc.Shared.Attributes;
 9namespace CodingMilitia.Grpc.Client.Internal
11    internal class GrpcClientTypeBuilder
12    {
13        public TypeInfo Create<TService>() where TService : class, IGrpcService
14        {
16            var assemblyName = Guid.NewGuid().ToString();
17            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);
18            var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);
20            var serviceType = typeof(TService);
21            var typeBuilder = moduleBuilder.DefineType(serviceType.Name + "Client", TypeAttributes.Public, typeof(GrpcClientBase));
23            typeBuilder.AddInterfaceImplementation(serviceType);
24            AddConstructor(typeBuilder, serviceType);
25            AddMethods(typeBuilder, serviceType);
27            return typeBuilder.CreateTypeInfo();
28        }
30        //...
31    }

The Create method starts by creating an assembly builder and a module builder, with a GUID as the name right now, maybe in the future I come up with some useful name, but right now it isn’t really relevant. Then a TypeBuilder is created, and the service client type starts to be defined. The client type implements the provided service interface and inherits from GrpcClientBase, an abstract class with some auxiliary methods to simplify the rest of the type definition. After defining the base class and interface implementation, the AddConstructor and AddMethods are called, wrapping up with returning a completely runtime generated type that represents the service client.

Before getting into AddConstructor and AddMethod, let’s take a quick look into GrpcClientBase.

 1using CodingMilitia.Grpc.Serializers;
 2using CodingMilitia.Grpc.Shared.Internal;
 3using System.Threading;
 4using System.Threading.Tasks;
 5using G = Grpc.Core;
 7namespace CodingMilitia.Grpc.Client.Internal
 9    public abstract class GrpcClientBase
10    {
11        private readonly G.Channel _channel;
12        private readonly G.DefaultCallInvoker _invoker;
13        private readonly ISerializer _serializer;
15        protected GrpcClientBase(GrpcClientOptions options, ISerializer serializer)
16        {
17            _channel = new G.Channel(options.Url, options.Port, G.ChannelCredentials.Insecure);
18            _invoker = new G.DefaultCallInvoker(_channel);
19            _serializer = serializer;
20        }
22        protected async Task<TResponse> CallUnaryMethodAsync<TRequest, TResponse>(TRequest request, string serviceName, string methodName, CancellationToken ct)
23            where TRequest : class
24            where TResponse : class
25        {
26            var callOptions = new G.CallOptions(cancellationToken: ct);
27            using (var call = _invoker.AsyncUnaryCall(GetMethodDefinition<TRequest, TResponse>(G.MethodType.Unary, serviceName, methodName), null, callOptions, request))
28            {
29                return await call.ResponseAsync.ConfigureAwait(false);
30            }
31        }
33        private G.Method<TRequest, TResponse> GetMethodDefinition<TRequest, TResponse>(G.MethodType methodType, string serviceName, string methodName)
34            where TRequest : class
35            where TResponse : class
36        {
37            return MethodDefinitionGenerator.CreateMethodDefinition<TRequest, TResponse>(methodType, serviceName, methodName, _serializer);
38        }
39    }

This class is rather simple (at least compared to what’s coming next) and simply makes use of gRPC’s core libraries to make service calls. The constructor receives some arguments to create the communication channel and a serializer like we saw earlier. The CallUnaryMethodAsync does exactly what the name says, invokes an unary method exposed by the service, making use of MethodDefinitionGenerator.CreateMethodDefinition to get the method definition like we also saw earlier.

Now for the first IL emitting part, invoking the base class constructor.

 1private void AddConstructor(TypeBuilder typeBuilder, Type serviceType)
 3    var ctorBuilder = typeBuilder.DefineConstructor(
 4        MethodAttributes.Public,
 5        CallingConventions.Standard,
 6        new[] { typeof(GrpcClientOptions), typeof(ISerializer) }
 7    );
 9    var il = ctorBuilder.GetILGenerator();
10    il.Emit(OpCodes.Ldarg_0); //load this
11    il.Emit(OpCodes.Ldarg_1); //load options
12    il.Emit(OpCodes.Ldarg_2); //load serializer
13    var clientBaseType = typeof(GrpcClientBase);
14    var ctorToCall = clientBaseType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(GrpcClientOptions), typeof(ISerializer) }, null);
15    il.Emit(OpCodes.Call, ctorToCall);//call base class constructor
16    il.Emit(OpCodes.Ret);

So, just to get this out of the way, I can’t write IL by heart, so I wrote the code I expected to obtain, went for the resulting IL and used it here (used .NET Fiddle to get the IL).

In summary, it’s defining a public constructor that receives GrpcClientOptions and ISerializer instances, then loading the arguments onto the stack to then call the base class constructor. Now you see why the base class? So I didn’t need to generate the whole IL, just the minimum necessary the call the base class and code the rest like usual.

Now for the AddMethods + AddMethod

 1private void AddMethods(TypeBuilder typeBuilder, Type serviceType)
 3    foreach (var method in serviceType.GetMethods())
 4    {
 5        AddMethod(typeBuilder, method);
 6    }
 9private void AddMethod(TypeBuilder typeBuilder, MethodInfo method)
11    var serviceName = ((GrpcServiceAttribute)method.DeclaringType.GetCustomAttribute(typeof(GrpcServiceAttribute))).Name ?? method.DeclaringType.Name;
12    var methodName = ((GrpcMethodAttribute)method.GetCustomAttribute(typeof(GrpcMethodAttribute))).Name ?? method.Name;
14    var args = method.GetParameters();
15    var methodBuilder = typeBuilder.DefineMethod(
16        method.Name,
17        MethodAttributes.Public | MethodAttributes.Virtual,
18        method.ReturnType,
19        (from arg in args select arg.ParameterType).ToArray()
20    );
21    var il = methodBuilder.GetILGenerator();
22    il.Emit(OpCodes.Ldarg_0); //load this
23    il.Emit(OpCodes.Ldarg_1); //load request
24    il.Emit(OpCodes.Ldstr, serviceName); //load constant service name as argument
25    il.Emit(OpCodes.Ldstr, methodName); //load constant method name as argument
26    il.Emit(OpCodes.Ldarg_2); //load cancellation token
27    var clientBaseType = typeof(GrpcClientBase);
28    var methodToCall = clientBaseType.GetMethod("CallUnaryMethodAsync", BindingFlags.Instance | BindingFlags.NonPublic);
32    il.Emit(
33        OpCodes.Call,
34        methodToCall.MakeGenericMethod(new[]{ //TODO: must check arguments and stuff
35            method.GetParameters()[0].ParameterType,
36            method.ReturnType.GetGenericArguments()[0]
37        })
38    ); //call base class method
40    il.Emit(OpCodes.Ret); //return (the return value is already on the stack )
42    typeBuilder.DefineMethodOverride(methodBuilder, method);

The AddMethods just loops through the service interface’s methods, but the AddMethod is where things go crazy again.

It starts with a simple fetching of the service and method names from the custom attributes discussed earlier. Then the code is similar to the discussed regarding the constructor - define the method, getting its argument types from the MethodInfo we’re using at the moment, then start emitting IL to load the arguments onto the stack to then call the base class CallUnaryMethodAsync method. Because CallUnaryMethodAsync is a generic method, there are some extra reflection hoops to jump through, but the method invocation is done like in the constructor code. To wrap up the return statement is emitted and the new method is defined as an override in the type builder.


Now this has gotten to be a longer post than what I expected, but I hope it’s useful for something.

Now to wrap it up, what does this do and what it doesn’t? Like I said along the way, I tried to cover only the most basic of scenarios to get a feel of what could be done, and by looking at the outcome, I think that with a little more work it is possible to support all the usual options that the core gRPC libraries provide, while making it more similar to other .NET technologies to start with.

If this is used in a purely .NET environment, we don’t even have to worry about proto files and stuff like that, but if we want interoperability with other techs, it’s better to create the service definition files, so the others can work as usual, although in this case this whole thing gets less useful.

So, just to make it clear, is it ready to production?… NO! (as if it wasn’t obvious by this time) But if it’s useful, I think it can get there, adding the missing parts, improving the API, making sure performance is on par with what we would get if using the core libraries as usual.

Even if this PoC doesn’t go any further, at least I got a excuse to play with some different stuff, including IL emitting :)

If you read this whole thing, thanks a lot for that! I hope it was useful. Cyaz!

Categories: dotnet
Tags: dotnet grpc services