0
votes

I have a .net core project file (*.csproj) like this:

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk" ToolsVersion="15.0">
  <!-- Create RS.cs -->
  <ItemGroup>
    <ResourceGeneratorInputs Include="strings.resx" />
    <ResourceGeneratorOutputs Include="RS.cs" />
  </ItemGroup>
  <Target Name="GenerateTheResourceFile" 
        BeforeTargets="PrepareForBuild" 
        Inputs="@(ResourceGeneratorInputs)" 
        Outputs="@(ResourceGeneratorOutputs)">
    <Exec Command="ResourceStringGenerator.exe strings.resx RS.cs " />
  </Target>
</Project>

This projects has a target that generates a csharp code file called RS.cs, which also must be compiled.

The problem is the file is generated too late. The build engine has already read the list of files in the project directory, and the RS.cs file gets ignored.

I have tried changing the BeforeTargets attribute to various other Targets with no luck at all. (Described here: https://docs.microsoft.com/en-us/dotnet/core/tools/csproj#build-events) I've tried turning off automatic inclusion of files too:

 <PropertyGroup>
    <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
  </PropertyGroup>

and making my own list of files to compile. But that didn't work either. The RS.cs file was still generated too late.

The new project file format seems to be so eager to get the list of files, that it seems to leave no room for auto-generated files.

What is the work-around here?

1

1 Answers

3
votes

The static portion of a project file is always evaluated before targets run. However, you can also add items inside your target:

<Target Name="GenerateTheResourceFile" 
      BeforeTargets="PrepareForBuild" 
      Inputs="@(ResourceGeneratorInputs)" 
      Outputs="@(ResourceGeneratorOutputs)">
  <Exec Command="ResourceStringGenerator.exe strings.resx RS.cs " />

  <ItemGroup>
    <EmbeddedResource Include="strings.resx" Exclude="@(EmbeddedResource)" />
    <Compile Include="RS.cs" Exclude="@(Compile)" />
  </ItemGroup>
</Target>

The "exclude" part ensures that the file isn't added twice if it was already picked up during static evaluation (i.e. additional builds)