Debian Codegraph @

src/csharp/BUILD-INTEGRATION.md

raw
1 Protocol Buffers/gRPC Codegen Integration Into .NET Build
2 =================================================
3
4 With Grpc.Tools package version 1.17 we made it easier to compile .proto files
5 in your project using the `dotnet build` command, Visual Studio, or command-line
6 MSBuild. You need to configure the .csproj project according to the way you want
7 to integrate Protocol Buffer files into your build.
8
9 There is also a Reference section at the end of the file.
10
11 Common scenarios
12 ----------------
13
14 ### I just want to compile .proto files into my library
15
16 This is the approach taken by the examples in the `csharp/examples` directory.
17 Protoc output files (for example, `Helloworld.cs` and `HelloworldGrpc.cs`
18 compiled from `helloworld.proto`) are placed among *object* and other temporary
19 files of your project, and automatically provided as inputs to the C# compiler.
20 As with other automatically generated .cs files, they are included in the source
21 and symbols NuGet package, if you build one.
22
23 Simply reference your .proto files in a `<Protobuf>` item group. The following
24 example will add all .proto files in a project and all its subdirectories
25 (excluding special directories such as `bin` and `obj`):
26
27 ```xml
28 <ItemGroup>
29 <Protobuf Include="**/*.proto" />
30 </ItemGroup>
31 ```
32
33 You must add a reference to the NuGet packages Grpc.Tools and Grpc (the latter
34 is a meta-package, in turn referencing Grpc.Core and Google.Protobuf packages).
35 It is **very important** to mark Grpc.Tools as a development-only dependency, so
36 that the *users* of your library do not fetch the tools package:
37
38 * "dotnet SDK" .csproj (Visual Studio, `dotnet new`): Add an attribute
39 `PrivateAssets="All"` to the Grpc.Tools package reference. See an example in the
40 [Greeter.csproj](../../examples/csharp/Helloworld/Greeter/Greeter.csproj#L10)
41 example project in this repository. If adding a package reference in Visual
42 Studio, edit the project file and add this attribute. [This is a bug in NuGet
43 client](https://github.com/NuGet/Home/issues/4125).
44
45 * "Classic" .csproj with `packages.config` (Visual Studio before 2017, old versions of Mono):
46 This is handled automatically by NuGet after you set the `developmentDependency="true"`
47 attribute on the `<package>` tag in `packages.config`.
48
49 If building a NuGet package from your library with the nuget command line tool
50 from a .nuspec file, then the spec file may (and probably should) reference the
51 Grpc metapackage, but **do not add a reference to Grpc.Tools** to it. "dotnet SDK"
52 projects handle this automatically when called from `dotnet pack` by excluding
53 any packages with private assets, such as thus marked Grpc.Tools.
54
55 #### Per-file options that can be set in Visual Studio
56
57 For a "dotnet SDK" project, you have more control of some frequently used options.
58 **You may need to open and close Visual Studio** for this form to appear in the
59 properties window after adding a reference to Grpc.Tools package (we do not know
60 whether this is a bug or by design, but it looks like a bug):
61
62 ![Properties in an SDK project](doc/integration.md-fig.2-sdk.png)
63
64 You can also change options of multiple files at once by selecting them in the
65 Project Explorer together.
66
67 For a "classic" project, you can only add .proto files with all options set to
68 default (if you find it necessary to modify these options, then hand-edit the
69 .csproj file). Click on the "show all files" button, add files to project, then
70 change file type of the .proto files to "Protobuf" in the Properties window
71 drop-down. This menu item will appear after you import the Grpc.Tools package:
72
73 ![Properties in a classic project](doc/integration.md-fig.1-classic.png)
74
75 See the Reference section at end of this file for options that can be set
76 per-file by modifying the source .csproj directly.
77
78 #### My .proto files are in a directory outside the project
79
80 Refer to the example files
81 [RouteGuide.csproj](../../examples/csharp/RouteGuide/RouteGuide/RouteGuide.csproj#L58-L60)
82 and [Greeter.csproj](../../examples/csharp/Helloworld/Greeter/Greeter.csproj#L11)
83 in this repository. For the files to show up in Visual Studio properly, add a
84 `Link` attribute with just a filename to the `<Protobuf>` item. This will be the
85 display name of the file. In the `Include` attribute, specify the complete path
86 to file. A relative path is based off the project directory.
87
88 Or, if using Visual Studio, add files _as links_ from outside directory. In the
89 Add Files dialog, there is a little [down arrow near the Open
90 button](https://stackoverflow.com/a/9770061). Click on it, and choose "Add as
91 link". If you do not select this option, Visual Studio will copy files to the
92 project directory instead.
93
94 Alternatively, you can also specify `AdditionalImportDirs` and provide a list of directories to search for imported .proto files. The directories are searched in the order given.
95
96 Eg.
97
98 ```xml
99 <Protobuf Include="protos/*.proto" ProtoRoot="protos"
100 AdditionalImportDirs="/folder/ouside/project/protos/myapis/;/another/folder/" ... />
101 ```
102
103 #### My .proto files have same filename in different folders
104
105 Starting from Grpc.Tools version 2.31, protocol buffers compilation preserves original folder structure for generated files. Eg.
106
107 - `../ProjectFolder/Protos/v2/http.proto`
108 - `../ProjectFolder/Protos/v3/http.proto`
109
110 Will result in:
111
112 - `../ProjectFolder/obj/CONFIGURATION/FRAMEWORK/Protos/v2/Greet.cs`
113 - `../ProjectFolder/obj/CONFIGURATION/FRAMEWORK/Protos/v2/GreetGrpc.cs`
114 - `../ProjectFolder/obj/CONFIGURATION/FRAMEWORK/Protos/v3/Greet.cs`
115 - `../ProjectFolder/obj/CONFIGURATION/FRAMEWORK/Protos/v3/GreetGrpc.cs`
116
117 This feature resolves problems we have faced in large projects. Moreover, There is now also a project-wide new option Protobuf_ProtoRoot to define the fallback ProtoRoot. If the ProtoRoot is set, this also reduces the amount of problems that lead to duplicates. Eg.
118
119 ```xml
120 <ItemGroup>
121 <Protobuf Include="Protos\v2\greet.proto" ProtoRoot="Protos" />
122 </ItemGroup>
123 ```
124
125 Before Grpc.Tools version 2.31 all .proto files were compiled into `obj` directory, flattening relative paths. For proto files with duplicated names it cause following errors `NETSDK1022 Duplicate 'Compile' items were included. [...]` or `MSB3105 [...] Duplicate items are not supported by the "Sources" parameter`. The workaround for this problem was introducing relative paths in your `obj` folder, by manipulating output path. Eg.
126
127 ```xml
128 <ItemGroup>
129 <Protobuf Include="Protos/v2/http.proto" OutputDir="$(Protobuf_OutputPath)%(RelativeDir)" />
130 <Protobuf Include="Protos/v3/http.proto" OutputDir="$(Protobuf_OutputPath)%(RelativeDir)" />
131 </ItemGroup>
132 ```
133
134 __Note, this was a workaround approach, we recommend updating Grpc.Tools to the latest version.__
135
136 ### I just want to generate proto and gRPC C# sources from my .proto files (no C# compile)
137
138 Suppose you want to place generated files right beside each respective source
139 .proto file. Create a .csproj library file in the common root of your .proto
140 tree, and add a reference to Grpc.Tools package (this works in Windows too, `$`
141 below stands for a command prompt in either platform):
142
143 ```
144 /myproject/myprotofiles$ dotnet new classlib
145 . . .
146 Restoring packages for /myproject/myprotofiles/myprotofiles.csproj...
147 . . .
148 /myproject/myprotofiles$ rm *.cs <-- remove all *.cs files from template;
149 C:\myproject\myprotofiles> del *.cs /y <-- on Windows, use the del command instead.
150 /myproject/myprotofiles$ dotnet add package Grpc.Tools
151 ```
152
153 (the latter command also accepts an optional `--version X.Y` switch for a
154 specific version of package, should you need one). Next open the generated
155 .csproj file in a text editor.
156
157 Since you are not building a package, you may not worry about adding
158 `PrivateAssets="All"` attribute, but it will not hurt, in case you are
159 repurposing the project at some time later. The important part is (1) tell the
160 gRPC tools to select the whole directory of files; (2) order placement of each
161 output besides its source, and (3) not compile the generated .cs files. Add the
162 following stanza under the `<Project>` xml node:
163
164 ```xml
165 <ItemGroup>
166 <Protobuf Include="**/*.proto" OutputDir="%(RelativeDir)" CompileOutputs="false" />
167 </ItemGroup>
168 ```
169
170 The `Include` tells the build system to recursively examine project directory
171 and its subdirectories (`**`) include all files matching the wildcard `*.proto`.
172 You can instead selectively include your files or selectively exclude files from
173 the glob pattern; [MSBuild documentation explains
174 that](https://docs.microsoft.com/visualstudio/msbuild/msbuild-items). The
175 `OutputDir="%(RelativeDir)"` orders the output directory for each .cs file be
176 same as the corresponding .proto directory. Finally, `CompileOutputs="false"`
177 prevents compiling the generated files into an assembly.
178
179 Note that an empty assembly is still generated, but you should ignore it. As
180 with any build system, it is used to detect out-of-date dependencies and
181 recompile them.
182
183 #### I am getting a warning about a missing expected file!
184
185 When we are preparing compile, there is no way to know whether a given proto
186 file will produce a *Grpc.cs output or not. If the proto file has a `service`
187 clause, it will; otherwise, it won't, but the build script cannot know that in
188 advance. When we are treating generated .cs files as temporary, this is ok, but
189 when generating them for you, creating empty files is probably not. You need to
190 tell the compiler which files should be compiled with gRPC services, and which
191 only contain protobuffer message definitions.
192
193 One option is just ignore the warning. Another is quench it by setting the
194 property `Protobuf_NoWarnMissingExpected` to `true`:
195
196 ```xml
197 <PropertyGroup>
198 <Protobuf_NoWarnMissingExpected>true</Protobuf_NoWarnMissingExpected>
199 </PropertyGroup>
200 ```
201
202 For a small to medium projects this is sufficient. But because of a missing
203 output dependency, the corresponding .proto file will be recompiled on every
204 build. If your project is large, or if other large builds depend on generated
205 files, and are also needlessly recompiled, you'll want to prevent these rebuilds
206 when files have not in fact changed, as follows:
207
208 ##### Explicitly tell protoc for which files it should use the gRPC plugin
209
210 You need to set the `Protobuf` item property `GrpcServices` to `None` for those
211 .proto inputs which do not have a `service` declared (or, optionally, those
212 which do but you do not want a service/client stub for). The default value for
213 the `GrpcServices` is `Both` (both client and server stub are generated). This
214 is easy enough to do with glob patterns if your files are laid out in
215 directories according to their service use, for example:
216
217 ```xml
218 <ItemGroup>
219 <Protobuf Include="**/*.proto" OutputDir="%(RelativeDir)"
220 CompileOutputs="false" GrpcServices="None" />
221 <Protobuf Update="**/hello/*.proto;**/bye/*.proto" GrpcServices="Both" />
222 </ItemGroup>
223 ```
224
225 In this sample, all .proto files are compiled with `GrpcServices="None"`, except
226 for .proto files in subdirectories on any tree level named `hello/` and `bye`,
227 which will take `GrpcServices="Both"` Note the use of the `Update` attribute
228 instead of `Include`. If you write `Include` by mistake, the files will be added
229 to compile *twice*, once with, and once without GrpcServices. Pay attention not
230 to do that!
231
232 Another example would be the use of globbing if your service .proto files are
233 named according to a pattern, for example `*_services.proto`. In this case, The
234 `Update` attribute can be written as `Update="**/*_service.proto"`, to set the
235 attribute `GrpcServices="Both"` only on these files.
236
237 But what if no patterns work, and you cannot sort a large set of .proto file
238 into those containing a service and those not? As a last resort,
239
240 ##### Force creating empty .cs files for missing outputs.
241
242 Naturally, this results in a dirtier compiler output tree, but you may clean it
243 using other ways (for example, by not copying zero-length .cs files to their
244 final destination). Remember, though, that the files are still important to keep
245 in their output locations to prevent needless recompilation. You may force
246 generating empty files by setting the property `Protobuf_TouchMissingExpected`
247 to `true`:
248
249 ```xml
250 <PropertyGroup>
251 <Protobuf_TouchMissingExpected>true</Protobuf_TouchMissingExpected>
252 </PropertyGroup>
253 ```
254
255 #### But I do not use gRPC at all, I need only protobuffer messages compiled
256
257 Set `GrpcServices="None"` on all proto files:
258
259 ```xml
260 <ItemGroup>
261 <Protobuf Include="**/*.proto" OutputDir="%(RelativeDir)"
262 CompileOutputs="false" GrpcServices="None" />
263 </ItemGroup>
264 ```
265
266 #### That's good so far, but I do not want the `bin` and `obj` directories in my tree
267
268 You may create the project in a subdirectory of the root of your files, such as,
269 for example, `.build`. In this case, you want to refer to the proto files
270 relative to that `.build/` directory as
271
272 ```xml
273 <ItemGroup>
274 <Protobuf Include="../**/*.proto" ProtoRoot=".."
275 OutputDir="%(RelativeDir)" CompileOutputs="false" />
276 </ItemGroup>
277 ```
278
279 Pay attention to the `ProtoRoot` property. It needs to be set to the directory
280 where `import` declarations in the .proto files are looking for files, since the
281 project root is no longer the same as the proto root.
282
283 Alternatively, you may place the project in a directory *above* your proto root,
284 and refer to the files with a subdirectory name:
285
286 ```xml
287 <ItemGroup>
288 <Protobuf Include="proto_root/**/*.proto" ProtoRoot="proto_root"
289 OutputDir="%(RelativeDir)" CompileOutputs="false" />
290 </ItemGroup>
291 ```
292
293 ### Alas, this all is nice, but my scenario is more complex, -OR-
294 ### I'll investigate that when I have time. I just want to run protoc as I did before.
295
296 One option is examine our [.targets and .props files](Grpc.Tools/build/) and see
297 if you can create your own build sequence from the provided targets so that it
298 fits your needs. Also please open an issue (and tag @kkm000 in it!) with your
299 scenario. We'll try to support it if it appears general enough.
300
301 But if you just want to run `protoc` using MsBuild `<Exec>` task, as you
302 probably did before the version 1.17 of Grpc.Tools, we have a few build
303 variables that point to resolved names of tools and common protoc imports.
304 You'll have to roll your own dependency checking (or go with a full
305 recompilation each time, if that works for you), but at the very least each
306 version of the Tools package will point to the correct location of the files,
307 and resolve the compiler and plugin executables appropriate for the host system.
308 These property variables are:
309
310 * `Protobuf_ProtocFullPath` points to the full path and filename of protoc executable, e. g.,
311 "C:\Users\kkm\.nuget\packages\grpc.tools\1.17.0\build\native\bin\windows\protoc.exe".
312
313 * `gRPC_PluginFullPath` points to the full path and filename of gRPC plugin, such as
314 "C:\Users\kkm\.nuget\packages\grpc.tools\1.17.0\build\native\bin\windows\grpc_csharp_plugin.exe"
315
316 * `Protobuf_StandardImportsPath` points to the standard proto import directory, for example,
317 "C:\Users\kkm\.nuget\packages\grpc.tools\1.17.0\build\native\include". This is
318 the directory where a declaration such as `import "google/protobuf/wrappers.proto";`
319 in a proto file would find its target.
320
321 Use MSBuild property expansion syntax `$(VariableName)` in your protoc command
322 line to substitute these variables, for instance,
323
324 ```xml
325 <Target Name="MyProtoCompile">
326 <PropertyGroup>
327 <ProtoCCommand>$(Protobuf_ProtocFullPath) --plugin=protoc-gen-grpc=$(gRPC_PluginFullPath) -I $(Protobuf_StandardImportsPath) ....rest of your command.... </ProtoCCommand>
328 </PropertyGroup>
329 <Message Importance="high" Text="$(ProtoCCommand)" />
330 <Exec Command="$(ProtoCCommand)" />
331 </Target>
332 ```
333
334 Also make sure *not* to include any file names to the `Protobuf` item
335 collection, otherwise they will be compiled by default. If, by any chance, you
336 used that name for your build scripting, you must rename it.
337
338 ### What about C++ projects?
339
340 This is in the works. Currently, the same variables as above are set to point to
341 the protoc binary, C++ gRPC plugin and the standard imports, but nothing else.
342 Do not use the `Protobuf` item collection name so that your project remains
343 future-proof. We'll use it for C++ projects too.
344
345 Reference
346 ---------
347
348 ### Protobuf item metadata reference
349
350 The following metadata are recognized on the `<Protobuf>` items.
351
352 | Name | Default | Value | Synopsis |
353 |----------------|-----------|----------------------|----------------------------------|
354 | Access | `public` | `public`, `internal` | Generated class access |
355 | AdditionalProtocArguments | | arbitrary cmdline arguments | Extra command line flags passed to `protoc` command. To specify multiple arguments use semi-colons (;) to separate them. See example below |
356 | ProtoCompile | `true` | `true`, `false` | Pass files to protoc? |
357 | ProtoRoot | See notes | A directory | Common root for set of files |
358 | CompileOutputs | `true` | `true`, `false` | C#-compile generated files? |
359 | OutputDir | See notes | A directory | Directory for generated C# files with protobuf messages |
360 | OutputOptions | | arbitrary options | Extra options passed to C# codegen as `--csharp_opt=opt1,opt2` |
361 | GrpcOutputDir | See notes | A directory | Directory for generated gRPC stubs |
362 | GrpcOutputOptions | | arbitrary options | Extra options passed to gRPC codegen as `--grpc_opt=opt1,opt2` |
363 | GrpcServices | `both` | `none`, `client`, `server`, `both` | Generated gRPC stubs |
364 | AdditionalImportDirs | See notes | Directories | Specify additional directories in which to search for imports .proto files |
365
366 __Notes__
367
368 * __ProtoRoot__
369 For files _inside_ the project cone, `ProtoRoot` is set by default to the
370 project directory. For every file _outside_ of the project directory, the value
371 is set to this file's containing directory name, individually per file. If you
372 include a subtree of proto files that lies outside of the project directory, you
373 need to set this metadatum. There is an example in this file above. The path in
374 this variable is relative to the project directory.
375
376 * __OutputDir__
377 The default value for this metadatum is the value of the property
378 `Protobuf_OutputPath`. This property, in turn, unless you set it in your
379 project, will be set to the value of the standard MSBuild property
380 `IntermediateOutputPath`, which points to the location of compilation object
381 outputs, such as "obj/Release/netstandard1.5/". The path in this property is
382 considered relative to the project directory.
383
384 * __GrpcOutputDir__
385 Unless explicitly set, will follow `OutputDir` for any given file.
386
387 * __Access__
388 Sets generated class access on _both_ generated message and gRPC stub classes.
389
390 * __AdditionalProtocArguments__
391 Pass additional commandline arguments to the `protoc` command being invoked.
392 Normally this option should not be used, but it exists for scenarios when you need to pass
393 otherwise unsupported (e.g. experimental) flags to protocol buffer compiler.
394
395 * __GrpcOutputOptions__
396 Pass additional options to the `grpc_csharp_plugin` in form of the `--grpc_opt` flag.
397 Normally this option should not be used as it's values are already controlled by "Access"
398 and "GrpcServices" metadata, but it might be useful in situations where you want
399 to explicitly pass some otherwise unsupported (e.g. experimental) options to the
400 `grpc_csharp_plugin`.
401
402 * __AdditionalImportDirs__
403 Specify additional directories in which to search for imports in .proto files. The directories are searched in the order given. You may specify directories _outside_ of the
404 project directory. The directories are passed to the `protoc` code generator via the `-I/--proto_path` option
405 together with `Protobuf_StandardImportsPath` and `ProtoRoot` directories.
406
407 __Specifying multiple values in properties__
408
409 Some properties allow you to specify multiple values in a list. The items in a list need to
410 be separated by semi-colons (;). This is the syntax that MsBuild uses for lists.
411
412 The properties that can have lists of items are: __OutputOptions__, __AdditionalProtocArguments__, __GrpcOutputOptions__, __AdditionalImportDirs__
413
414 Example: to specify two additional arguments: ```--plugin=protoc-gen-myplugin=D:\myplugin.exe --myplugin_out=.```
415
416 ```xml
417 <ItemGroup>
418 <Protobuf Include="proto_root/**/*.proto" ProtoRoot="proto_root"
419 OutputDir="%(RelativeDir)" CompileOutputs="false"
420 AdditionalProtocArguments="--plugin=protoc-gen-myplugin=D:\myplugin.exe;--myplugin_out=." />
421 </ItemGroup>
422 ```
423
424 `grpc_csharp_plugin` command line options
425 ---------
426
427 Under the hood, the `Grpc.Tools` build integration invokes the `protoc` and `grpc_csharp_plugin` binaries
428 to perform code generation. Here is an overview of the available `grpc_csharp_plugin` options:
429
430 | Name | Default | Synopsis |
431 |---------------- |-----------|----------------------------------------------------------|
432 | no_client | off | Don't generate the client stub |
433 | no_server | off | Don't generate the server-side stub |
434 | internal_access | off | Generate classes with "internal" visibility |
435
436 Note that the protocol buffer compiler has a special commandline syntax for plugin options.
437 Example:
438 ```
439 protoc --plugin=protoc-gen-grpc=grpc_csharp_plugin --csharp_out=OUT_DIR \
440 --grpc_out=OUT_DIR --grpc_opt=lite_client,no_server \
441 -I INCLUDE_DIR foo.proto
442 ```