Skip to content

Localization Generator

Do you use Microsoft.Extensions.Localization? It provides a great set of abstractions, but it removes the IDE tooling that provided strong typing of the available keys. This library looks to solve that by generating a class around a IStringLocalizer class.

Given this directory structure:

  • MyViewModel.cs
  • MyViewModel.resx
  • MyViewModel.fr-ca.rex
  • Folder1\FolderViewModel.cs
  • Folder1\FolderViewModel.resx
  • Folder1\FolderViewModel.fr-ca.resx

We will generate these:

  • MyViewModelLocalized.g.cs (RootNamespace.MyViewModelLocalized)
  • Folder1.FolderViewModelLocalized.g.cs (RootNamespace.Folder1.FolderViewModelLocalized)
  • ServiceCollections.g.cs
  1. Install
  2. Install
  3. In your MauiProgram.cs, do the following
    builder.Services.AddStronglyTypedLocalizations(); // this will also add the AddLocalization() call
  4. Now add an .resx file to your project that matches the name of class (ie. ViewModel, Controller, Service, etc).
  5. 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}" />

If the “class” beside the resource does not exist, a compile error will occur with the generated code

<PropertyGroup>
<GenerateLocalizersInternal>True</GenerateLocalizersInternal>
</PropertyGroup>