Microsoft.Extensions.Localization Strongly Typed Class Generator
July 3, 2025 ยท View on GitHub
Generates strongly typed classes for resources to be used by IStringLocalizer from Microsoft.Extensions.Localizer This is very much adapted (and a bunch copied) code from https://github.com/VocaDB/ResXFileCodeGenerator
This directory structure:
- MyViewModel.cs
- MyViewModel.resx
- MyViewModel.fr-ca.rex
- Folder1\FolderViewModel.cs
- Folder1\FolderViewModel.resx
- Folder1\FolderViewModel.fr-ca.resx
Will generate:
- MyViewModelLocalized.g.cs (RootNamespace.MyViewModelLocalized)
- Folder1.FolderViewModelLocalized.g.cs (RootNamespace.Folder1.FolderViewModelLocalized)
- ServiceCollections.g.cs
To use this:
- Install Microsoft.Extensions.Localization
- Install Shiny.Extensions.Localization.Generator
- In your MauiProgram.cs, do the following
builder.Services.AddLocalization();
builder.Services.AddStronglyTypedLocalizations();
- Now add an
.resxfile to your project that matches the name of class (ie. ViewModel, Controller, Service, etc). - Now inject the strongly typed classes
public class MyViewModel
{
public MyViewModel(MyViewModelLocalized localizer) // same namespace and class name with "Localized" suffix
=> this.Localizer = localizer;
public MyViewModelLocalized Localizer { get; }
}
6.Now bind (xaml intellisense will pick it up)
<Label Text="{Binding Localizer.MyKey}" />
Warning
If the "class" beside the resource does not exist, a compile error will occur with the generated code
Generate Classes with Internal Accessor
<PropertyGroup>
<GenerateLocalizersInternal>True</GenerateLocalizersInternal>
</PropertyGroup>