I had an issue where a Roslyn source generator was not being called at all in a .NET project, the breakpoint of the Initialize method did not hit, while the launchSettings.json was correct and it did in fact work for some other projects.
The cause was a filename with a space at the end before the .cs extension, in my example it was: ValueTypeMapping .cs
Because of this trailing space, Roslyn silently skipped analyzers and source generators during the build for the project — without any indication or error messages. I did do /bl build and had the MS build structured log viewer where it didn't look like it had anything, I also did a /pp build and that proved the analyzer was not passed <Analyzer Include= should show {SourceGeneratorName}.dll, which it didn't.
To prevent this in the future, I added a build validation step to fail fast if any file has a trailing space:
<Target Name="ValidateNoTrailingSpacesInFileNames" BeforeTargets="CoreCompile">
<ItemGroup>
<!-- Check if the Filename part (without extension) ends with a space using Regex -->
<FilesWithTrailingSpaces
Include="@(Compile)"
Condition="'%(Filename)' != '' AND $([System.Text.RegularExpressions.Regex]::IsMatch('%(Filename)', '\s$'))"
/>
<!-- Explanation:
'$([System.Text.RegularExpressions.Regex]::IsMatch('%(Filename)', '\s$'))'
Calls the static Regex.IsMatch method.
Input: '%(Filename)'
Pattern: '\s$' (whitespace \s at the end $)
MSBuild evaluates the boolean result ('True'/'False') directly in the condition.
-->
</ItemGroup>
<Error
Text="File '%(FilesWithTrailingSpaces.Identity)' has trailing spaces before its extension (Filename: '%(FilesWithTrailingSpaces.Filename)'). Please rename it."
Condition="@(FilesWithTrailingSpaces) != ''" />
</Target>
To my Directory.Build.props file (on the repository level).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With