How do I generate .Designer.cs files from resx files as part of dotnet build

674 Views Asked by At

.Designer.cs files are generated automatically by Visual Studio or Rider (and probably other IDEs), but it is not a part of build process. I want to generate these files as a part of build process using dotnet build. That way I don't have to put these generated files to source control where they cause a lot of conflicts. How to achieve this?

1

There are 1 best solutions below

0
aksu On BEST ANSWER

The original inclusion in templates and examples in .csproj project files looks like this:

<ItemGroup>
  <EmbeddedResource Update="Resources\Resource.resx">
    <Generator>PublicResXFileCodeGenerator</Generator>
    <LastGenOutput>Resource.Designer.cs</LastGenOutput>
  </EmbeddedResource>
</ItemGroup>

This generates the Resource.Designer.cs in IDEs like described in the question using PublicResXFileCodeGenerator.

To generate the file in build process requires a bit more configuration, and you have to know the generated class and namespace names:

<EmbeddedResource Update="Resources\Resource.resx">
  <Generator>MSBuild:Compile</Generator>
  <StronglyTypedFileName>
    $(IntermediateOutputPath)\Resource.Designer.cs
  </StronglyTypedFileName>
  <StronglyTypedLanguage>CSharp</StronglyTypedLanguage>
  <StronglyTypedNamespace>Example.Resources</StronglyTypedNamespace>
  <StronglyTypedClassName>Resource</StronglyTypedClassName>
</EmbeddedResource>

Here the generator is the build process, StronglyTypeFileName tells the path where the .Designer.cs file is generated to (obj-folder), language that is used (in my case C#) and finally the namespace and class name. If you have multiple resource files for instance for different languages, you might have Resource_en as a class name for English.

Solution adapted from https://github.com/dotnet/msbuild/issues/2272 I also found a good blog post describing the solution here https://www.paraesthesia.com/archive/2022/09/30/strongly-typed-resources-with-net-core/