Using Microsoft Bond in a C# project

yuvalm2 picture yuvalm2 · Sep 19, 2016 · Viewed 7.6k times · Source

Is there a standard way to reference a Microsoft Bond schema file in a C# project?

Answer

chwarr picture chwarr · Sep 22, 2016

For a SDK-style .csproj files

When you add a PackageReference to the NuGet package Bond.CSharp in a SDK-style .csproj file (like the ones used with .NET Core or .NET 5+), the types from any .bond files in your project directory will be included in your assembly:

<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="Bond.CSharp" Version="9.0.3" />
  </ItemGroup>
</Project>

Code gen will be run on all the .bond files in the project directory and the resulting .cs files will be compiled into your assembly.

The MSBuild item BondCodegen is used to collect the .bond files to process. You can use MSBuild's Update and Remove functionality to customize the items included in codegen.

For even more details about what the targets support, like the metadata that can be used to customize codegen, check out the Bond.CSharp package README or the targets themselves. (Note that any property/target that starts with an underscore in a private property. These properties are not part of the public interface of the codegen targets and could change at any time.)

The Bond.CSharp package pulls in many other Bond packages to get the full functionality of Bond serialization, which is usually what you want. However, there are finer-grained packages that you can also use for more precise control over dependencies (e.g., to not add a dependency on Newtonsoft.JSON).

For "classic" .csproj files

When you use Visual Studio to add a reference to the NuGet package Bond.CSharp, NuGet will add a reference to the Bond codegen .targets file to the .csproj file. This .targets file, will automatically run codegen on any .bond file in the BondCodegen ItemGroup, and the resulting .cs file will implicitly compiled.

In Visual Studio, this is controlled by changing the file's "Build Action" in its properties.

There's a simple example showing how the BondCodegen ItemGroup works in the Bond source tree. An excerpt of what that .csproj file looks like:

<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  ...
  <Import Project="..\..\..\..\cs\build\nuget\Bond.CSharp.props" />
  ...
  <ItemGroup>
    <BondCodegen Include="schema.bond" />
  </ItemGroup>
  ...
  <Import Project="$(BOND_PATH)\build\nuget\Bond.CSharp.targets" />
</Project>