Code-First gRPC in .NET: The Interface Is the Contract, and So Are the Messages
A shared C# interface gives .NET services gRPC calls you can find, compile, and refactor. It only stays safe if the messages carry real fields with fixed numbers, endpoints deny by default, and tests check the previous release, not just the current build.
A customer opens an old order and taps Buy again. The service that handles the tap knows which order the customer picked. A different service owns the cart, and only it can say what can be added today. It might add two items and skip a third because it is out of stock. The caller needs both answers, the new cart and the skipped items, before it sends the customer to checkout.
That is one remote call between two .NET services. How you define it decides whether the next developer can find it, whether the compiler catches a mismatch, and whether a rolling deploy quietly drops the order reference halfway through.
This article is for .NET engineers who connect their own services with gRPC and want to skip .proto files without losing what they give you. It covers the contract, the messages, how clients and endpoints get wired by convention, channel settings, errors, and the tests that catch the breaks a clean build cannot. I also cover when to write the .proto anyway.
Why code-first between .NET services
gRPC is usually contract-first. You write a .proto file, run a code generator, and implement the generated base class. That is the right default when clients are written in other languages.
When both ends are C#, protobuf-net.Grpc lets a plain interface play that role. The interface lives in a shared contracts assembly. The server implements it. The client gets a generated proxy that implements the same interface, so constructor injection works like any other dependency.
| Aspect | .proto first | Code-first (shared interface) |
|---|---|---|
| Source of truth | .proto file | C# interface and message classes |
| Build step | protoc or Grpc.Tools codegen | None |
| Find all callers | Search generated names | Find references on the method |
| Cross-language clients | Native | Export a .proto from the C# types |
| Wire format | Protobuf | Protobuf (same) |
| Breaking-change checks | buf breaking and similar | Your own snapshot and compatibility tests |
The last row is the catch. Code-first removes the codegen step, and with it the tooling that guards the schema. The rest of this article is mostly about putting that guard back.
Name the operation, not the transport
The contract for Buy again is one method on the cart service's interface.
[ServiceContract]
[ServiceOwner(Owner.Cart)]
public interface ICartService : IRpcContract
{
[OperationContract]
Task<RebuildCartReply> RebuildCartAsync(
RebuildCartRequest request, CallContext context = default);
}
Three details carry weight:
- A named method per operation. "Find references" on
RebuildCartAsynclands on every caller. AnExecuteAsync(command)style method would hide the operation inside a string or a type switch. CallContexton every method. It carries the cancellation token, deadline, and metadata. A method without it cannot be cancelled by the caller.IRpcContractand[ServiceOwner]. These are my own conventions, not library types. The marker interface makes the contract discoverable at startup. The owner attribute says which service hosts it. Both come back in the wiring sections below.
Adding an operation to an existing service is three edits: a method on the interface, an implementation on the host, a call at the call site. Address, client registration, and endpoint mapping already exist for the service, so nothing else changes.
The lesson: messages are the contract too
The first version of the contracts I worked with took a shortcut. Every operation accepted and returned the same envelope: a Protobuf message with a single string field, and JSON inside it. In practice every method looked like Task<Envelope> RebuildCartAsync(Envelope request).
It was quick to adopt. One message type covered every call, and any existing model could be serialized into it. The costs showed up later:
- The compiler checks the envelope, not the payload.
RebuildCartAsynccompiles whether the JSON inside describes an order or a refund. - Tools see a string. A gRPC client, a log, or a proxy that inspects Protobuf shows one opaque field.
- Renames break deploys silently. Rename
OrderIdtoOrderReferencein the JSON model, rebuild both sides, and every test passes. During a rolling deploy the old caller still sendsOrderId. The envelope matches on both sides, so the call succeeds and the handler gets an empty reference. - Two serializers, two sets of rules. JSON naming, null handling, and enum formatting now matter inside a Protobuf call.
The shape I recommend is a real message per operation, with explicit field numbers.
[ProtoContract]
public sealed class RebuildCartRequest
{
[ProtoMember(1)] public string OrderId { get; set; } = "";
[ProtoMember(2)] public string StoreId { get; set; } = "";
// 3 was ShopperName. Removed. Never reuse 3.
[ProtoMember(4)] public string ShopperId { get; set; } = "";
}
[ProtoContract]
public sealed class RebuildCartReply
{
[ProtoMember(1)] public string? CartId { get; set; }
[ProtoMember(2)] public List<SkippedItem> Skipped { get; set; } = [];
}
Now the compiler knows what the cart service needs. A rename in C# does not change the wire, because the field number is what travels. And the reply says exactly what the caller must handle: maybe a cart, maybe skipped items, maybe both.
[ProtoContract]
public sealed class SkippedItem
{
[ProtoMember(1)] public string ProductId { get; set; } = "";
[ProtoMember(2)] public SkipReason Reason { get; set; }
}
public enum SkipReason { Unspecified = 0, OutOfStock = 1, Discontinued = 2 }
The enum starts at zero with Unspecified. Protobuf defaults a missing enum to zero, so zero must mean "unknown", never a real reason.
Field numbers are forever
Protobuf identifies fields by number, not name. That is what makes renames safe, and it is also the trap in code-first.
protobuf-net can build a model at runtime without attributes, and a convention that numbers properties in reflection order is tempting. It saves attributes on every class. It also means:
- Inserting a property in the middle renumbers every property after it.
- Field numbers depend on
GetProperties()order, which .NET does not guarantee. - A reader built yesterday decodes field 2 with yesterday's meaning.
None of these fail a build. They fail on the wire during a deploy, when old and new processes talk to each other.
My rules for any message that crosses a service boundary:
- Every member has an explicit
[ProtoMember(n)]. - New fields get new numbers at the end.
- A removed field's number is retired, with a comment, and never reused.
- Changing a field's type is a new field, not an edit.
The Protocol Buffers guidance on field numbers says the same, and it applies even when the schema is written in C#.
One attribute tells the client where the owner lives
When a constructor asks for ICartService, the container needs two things: an address, and something that turns calls on the interface into gRPC calls. I register every client from the contracts assembly at startup.
public static IServiceCollection AddRpcClients(this IServiceCollection services, Assembly contracts)
{
var addClient = typeof(RpcClientRegistration)
.GetMethod(nameof(AddClient), BindingFlags.NonPublic | BindingFlags.Static)!;
foreach (var contract in contracts.GetExportedTypes()
.Where(t => t.IsInterface && typeof(IRpcContract).IsAssignableFrom(t)))
{
var owner = contract.GetCustomAttribute<ServiceOwnerAttribute>()
?? throw new InvalidOperationException($"{contract.Name} is missing [ServiceOwner].");
var client = (IHttpClientBuilder)addClient.MakeGenericMethod(contract)
.Invoke(null, [services, owner.Service])!;
client.ConfigureRpcChannel();
}
return services;
}
The scan fails at startup if a contract has no owner. That is deliberate. A missing attribute should stop the host on a developer's machine, not throw a null reference on the first call in production.
Each client is one call to AddCodeFirstGrpcClient from the protobuf-net.Grpc.ClientFactory package.
private static IHttpClientBuilder AddClient<TContract>(IServiceCollection services, Owner owner)
where TContract : class
{
return services.AddCodeFirstGrpcClient<TContract>((sp, options) =>
options.Address = sp.GetRequiredService<IOptions<ServiceEndpoints>>().Value.For(owner));
}
Two libraries split the work behind that call. It is a normal Grpc.Net.ClientFactory registration underneath, so the .NET client factory owns the address, the HTTP handler, and interceptors. protobuf-net.Grpc turns the factory's call invoker into an object that implements the interface, using the same marshalling rules as the server. The method returns the IHttpClientBuilder, which is where the shared channel settings below are attached. Because the address comes from options keyed by owner, moving the cart service to a new host is a configuration change.
The host that implements the contract serves it
The server side mirrors the client. Each host scans its own assembly for classes that implement a contract and maps them as gRPC endpoints. Several hosts may reference ICartService to call it. Only the host that contains the implementation serves it.
This is also where authorization belongs, and the default matters. An endpoint should require authorization unless it explicitly opts out.
public static void MapRpcServices(this IEndpointRouteBuilder endpoints, Assembly host)
{
var map = typeof(GrpcEndpointRouteBuilderExtensions)
.GetMethods()
.Single(m => m.Name == nameof(GrpcEndpointRouteBuilderExtensions.MapGrpcService)
&& m.GetParameters().Length == 1);
foreach (var service in host.GetExportedTypes()
.Where(t => t is { IsClass: true, IsAbstract: false }
&& typeof(IRpcContract).IsAssignableFrom(t)))
{
var endpoint = (GrpcServiceEndpointConventionBuilder)map
.MakeGenericMethod(service).Invoke(null, [endpoints])!;
if (service.GetCustomAttribute<AllowAnonymousAttribute>() is null)
endpoint.RequireAuthorization(RpcPolicies.ServiceToService);
}
}
A convention that only adds authorization when it finds an attribute fails open: forget the attribute, and the endpoint is public. A convention that adds it unless told otherwise fails closed: forget the attribute, and the caller gets Unauthenticated in the first test. When endpoints are discovered by reflection, nobody reviews a list of routes, so the safe default has to be in the code.
Tune the channel once, in one place
Service-to-service gRPC runs over long-lived HTTP/2 connections. A few settings decide how those connections behave under load and across idle periods. I set them in the shared registration so every client gets the same behavior.
public static IHttpClientBuilder ConfigureRpcChannel(this IHttpClientBuilder client) =>
client
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
KeepAlivePingDelay = TimeSpan.FromSeconds(60),
KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
EnableMultipleHttp2Connections = true,
})
.ConfigureChannel(channel => channel.ThrowOperationCanceledOnCancellation = true)
.AddInterceptor<CallerTokenInterceptor>()
.AddInterceptor<RpcLoggingInterceptor>();
What each one buys:
- Keep-alive pings detect a dead connection before a real call waits on it. Load balancers drop idle connections without telling either side.
- Multiple HTTP/2 connections stop one connection's stream limit from queuing calls when traffic spikes.
ThrowOperationCanceledOnCancellationturns a cancelled call intoOperationCanceledException, which the rest of an ASP.NET Core app already handles.- Interceptors forward the caller's token and log each call, so cross-cutting work stays out of every handler.
Set the handler in exactly one place. The client factory owns the handler's lifetime, so configure it with ConfigurePrimaryHttpMessageHandler, not again through the channel's options. Configure it twice and you are left guessing which settings are actually in effect.
I keep message size limits near the 4 MB default. Raising them to fit a large list over gRPC treats the symptom. Page the list, or stream it with a server-streaming method.
Status codes for failure, fields for partial success
gRPC has two ways to say something went wrong, and Buy again needs both.
A failure means the operation did not happen: the order does not exist, the caller is not allowed, the deadline passed. That is a status code, thrown on the server and caught as RpcException on the client.
A partial success means the operation happened with caveats: the cart exists, but one item was skipped. That belongs in the reply, because the caller must act on it.
public async Task<RebuildCartReply> RebuildCartAsync(
RebuildCartRequest request, CallContext context = default)
{
var ct = context.CancellationToken;
var order = await orders.FindAsync(request.OrderId, ct)
?? throw new RpcException(new Status(StatusCode.NotFound, "Order not found."));
var result = await carts.AddAvailableItemsAsync(order, ct);
return new RebuildCartReply { CartId = result.CartId, Skipped = result.Skipped };
}
The caller sets a deadline on every call. Without one, a stuck cart service holds the customer's request until something else times out.
var reply = await cart.RebuildCartAsync(
request,
new CallOptions(deadline: DateTime.UtcNow.AddSeconds(3), cancellationToken: ct));
The test I care most about for this flow is on the caller. It has the cart double return a cart and a skipped item. It then checks that the caller still takes the checkout path and passes the warning on to the customer. That assertion describes the promise behind the button. A test that only checks the remote method was called once does not.
Test the previous release, not just this build
A rebuilt client and a rebuilt server always agree with each other. The breaks happen between versions, so the tests have to involve the previous version.
A schema snapshot. protobuf-net can print the .proto equivalent of a message. I commit that output and compare against it in a test.
[Fact]
public void Rebuild_cart_schema_matches_the_published_snapshot()
{
var schema = Serializer.GetProto<RebuildCartRequest>();
var snapshot = File.ReadAllText("Schemas/rebuild-cart-request.proto");
// Normalize line endings so a Windows checkout and a Linux CI agent agree.
Assert.Equal(snapshot.ReplaceLineEndings(), schema.ReplaceLineEndings());
}
When the test fails, the diff shows exactly what changed on the wire. A renumbered field or a changed type is visible in review, where it can be stopped.
A previous-release payload. I keep bytes written by the last release and decode them with the current reader.
[Fact]
public void Request_from_previous_release_still_decodes_the_order()
{
using var stream = File.OpenRead("Fixtures/rebuild-cart-request.previous.bin");
var request = Serializer.Deserialize<RebuildCartRequest>(stream);
Assert.Equal("order-1042", request.OrderId);
Assert.Equal("store-7", request.StoreId);
}
Assert on the decoded values, not on "it deserialized". Protobuf skips unknown fields and fills missing ones with defaults, so a broken contract usually deserializes without an error. An empty OrderId is the failure, and only a value assertion sees it.
When I write the .proto anyway
Code-first is a choice for services one team builds in C# on both ends. I switch to a .proto file when:
- A client is written in another language. The
.protois what their tooling consumes. Exporting one from C# works, but the C# types are no longer the only audience. - The API is published to partners. A public schema deserves review as a schema, with a breaking-change check in CI.
- Several teams own the contract. A neutral file in its own repository stops one team's C# refactor from reshaping another team's API.
In those cases I keep the same message rules: explicit numbers, retired numbers, typed fields, and a reply that states partial success.
What I take to the next service boundary
- A shared interface with one named method per operation, each taking
CallContext. - A real message per operation, with explicit
[ProtoMember]numbers that are never reused. - A marker and an owner attribute, so clients and endpoints register by convention and fail fast when one is missing.
- Endpoints that require authorization unless they explicitly opt out.
- Channel settings and interceptors configured once, in shared registration.
- Status codes for failure, reply fields for partial success, a deadline on every call.
- A schema snapshot and a previous-release payload in the test suite.
The interface is what makes code-first pleasant: you can open the Buy again call site and jump straight to the method its owner implements. The messages, the defaults, and the tests are what make it safe to deploy.