codemann8
codemann8

Reputation: 390

gRPC C# Specifying the namespace for the generated .cs files

I've followed the gRPC C# tutorial to generate and use .cs files using a source .proto file. The tutorial example gives a namespace to the .cs files, but when I try for my .proto file, there is NO namespace being applied whatsoever. The .proto file is externally controlled, so I have no control over the contents. Also, there are NO 'options' in the .proto for 'csharp-namespace'.

I'm using the (Visual Studio / NuGet + Build) method to generate these files. How do I specify a namespace for these objects?

For reference, I'm using this .proto file. As you can see, the generically-named 'Devices' service is causing some name conflicts in my project. It would seem odd to me that as a gRPC-client-developer, as in the one building a client to wrap a service, that you don't have control over its namespace.

Upvotes: 1

Views: 3900

Answers (1)

CodeReaper
CodeReaper

Reputation: 895

from https://developers.google.com/protocol-buffers/docs/csharptutorial

In C#, your generated classes will be placed in a namespace matching the package name if csharp_namespace is not specified. In our example, the csharp_namespace option has been specified to override the default, so the generated code uses a namespace of Google.Protobuf.Examples.AddressBook instead of Tutorial.

option csharp_namespace = "Google.Protobuf.Examples.AddressBook";

Did you try passing this option to protoc ?

It would seem odd to me that ... you don't have control over its namespace.

There are 3 options available for you.

  1. Easiest which you already know (but don't want to do?) just manually update the file in place. Done!
  2. If its a one time thing, and for whatever reason you don't want to modify the proto file, download the code generator from here and run protoc against those proto files which will generate C# classes similar to what Visual Studio Build is doing. You can then include the generated C# files in your solution. You must now leave out the proto file from your project OR set its Build Action to None if you do include it.
  3. If there are a lot of proto files and they will be changing frequently, you need to enhance step (2). You would want c# files generated as part of your MSBuild. You can do fancy (or really overengineer) things here like host the protos in a package externally, and MSBuild will download it during build. This step would need to happed before you can open your project in IDE else it will complain about missing C# files. n.b. these auto generated files will be part of project but not checked in to your source control. Your CI process will follow the same MSBuild process and generate files before it builds solution.

You get the idea. Basically you have a lot of options and control over the namspacing. Just not one that work out of the box.

Upvotes: 3

Related Questions