Search code examples
c#.netmsbuildflatbufferspre-build-event

Include source files generated by prebuild-event


I want to generate C# classes from a flatbuffer schema, and consume these classes in another project.

For this I need to invoke the flatbuffer schema compiler to generate the classes. I do not want to check in the class-files, but rather generate them during the build process, such that I do not need to update them manually.

Assume a C# solution with two projects:

MessageDefinitions.csproj
MessageConsumer.csproj

MessageDefinitions contains a prebuild event, which invokes the flatbuffer schema compiler and puts the generated C# source files into the folder MessageDefinitions/Messages/.

I then want to consume the generated types in MessageConsumer (which has a reference to MessageDefinitions).

The problem is that the compiled MessageDefinitions.dll does not contain the generated types, and thus building MessageConsumer fails. If I compile a second time, the build succeeds, as the files in MessageDefinitions/Messages/ already exist and are included in the compiled output.

Is there a way to make the compiler include the source files generated by the prebuild-event in MessageDefinitions on the first build?

Any help is appreciated, Kind regards.


Solution

  • Add something like the following to MessageDefinitions.csproj. I adapted and simplified it from the gist AddGeneratedFile.csproj by the author of MSBuild Structured Log Viewer (a tool a strongly recommend taking advantage of when working with MSBuild).

      <PropertyGroup>
        <MessageClassesPath>MessageDefinitions/Messages/**/*.cs</MessageClassesPath>
      </PropertyGroup>
    
      <Target Name="AddMessageClasses" AfterTargets="PreBuildEvent" BeforeTargets="BeforeCompile;CoreCompile">
        <ItemGroup>
          <Compile Include="$(MessageClassesPath)" />
        </ItemGroup>
      </Target>