Skip to content

About

A library for .NET that can help you to manage the localization in your application. The library includes Wpf extension, Xamarin extension, MAUI extension and Mvc extension.

Topics

Resources

Security policy

Stars

4 stars

Watchers

1 watching

Forks

Latest commit

 

History

373 Commits

Folders and files

Repository files navigation

Localization

NuGet Downloads Build License: MIT CodeQL .NET

Mafe.Localization downloads

Mafesoft.Localization is a .NET library to translate your application from vocabularies you load from any source — a database, a web API, a cache — through a small provider you write, or with the ready-made providers for JSON files and existing .resx files. The culture can be changed at runtime: every bound text (XAML, Razor, Blazor) is refreshed immediately, without restarting the application, also for right-to-left languages. The same API works in WPF, .NET MAUI, ASP.NET Core MVC and Blazor, and the .NET 10 builds are trimming and NativeAOT compatible.

Version 4.0.0: the packages are now published as Mafesoft.* and all the namespaces start with Mafesoft.. If you are using the Mafe.Localization* packages, read Migrating from Mafe.Localization.

The changes of every release are listed in the CHANGELOG. To report a security problem, read the security policy.

If Mafesoft.Localization is useful to you, consider supporting the project. ☕

Table of contents

Why Localization

.resx files and IStringLocalizer are compiled into the application: changing a translation means a new build and a new deploy, and switching language usually means reloading the UI. Mafesoft.Localization is built for the other case:

  • Vocabularies from any source. You write an IVocabularyServiceProvider that loads the terms of a culture from wherever they live: a database edited by your translators, a remote API, a cache. For JSON files and existing .resx files the provider is ready-made.
  • Culture change at runtime. SetCulture loads the new vocabulary and notifies the bindings: XAML labels, Razor views and Blazor components show the new language immediately.
  • The same API everywhere. LocalizationManager, Translate("key", "default") and the {culture:Translate} markup extension work the same way in WPF, .NET MAUI, ASP.NET Core MVC and Blazor.
  • Missing terms are reported. When a key is not in the vocabulary, the provider is notified (AddOrUpdateTermAsync), so it can store the new key and your translators see what is missing.

Features

  • Pluggable vocabulary provider (IVocabularyServiceProvider), synchronous or asynchronous initialization.
  • Runtime culture switch with SetCulture / SetCultureAsync and the CultureChanged event.
  • Default values: Translate("key", "#Default") never returns null.
  • Format arguments formatted with the culture of the vocabulary: TranslateFormat("Welcome", userName, count) (since 4.3.0).
  • Culture fallback it-IT → it → invariant → fallback culture, opt-in (UseParentCultureFallback, FallbackCulture, since 4.3.0).
  • XAML markup extension {culture:Translate Key, DefaultValue=..., StringFormat=...} for WPF and .NET MAUI.
  • ASP.NET Core MVC: [Translate] attribute, used by Html.LabelFor, <label asp-for>, Html.DisplayNameFor and the validation messages, plus TranslateLabelFor / TranslateLabel helpers and the <translate> / loc-key tag helpers (since 4.3.0), translated validation messages (AddValidationMessageTranslation, since 4.3.0).
  • Blazor Server and Blazor WebAssembly: Binding.Translate with default value and StringFormat, and the <Translate> component (since 4.3.0).
  • IStringLocalizer / IStringLocalizerFactory backed by the vocabularies, for DataAnnotations and the other consumers of Microsoft.Extensions.Localization (since 4.1.0).
  • Per-request culture on the server (FollowCurrentUICulture, with UseRequestLocalization()) and vocabularies cached per culture (since 4.1.0).
  • Ready-made JSON provider: one file per culture, flat or nested keys, embedded resources, a directory or an IFileProvider, reload when a file is saved, missing keys written for the translators (Mafesoft.Localization.Json, since 4.4.0). System.Text.Json by default, Newtonsoft.Json with Mafesoft.Localization.Json.Newtonsoft.
  • Typed keys: a source generator creates a class of constants from the JSON vocabularies, and the MLOC001 analyzer warns about keys that are not in the vocabulary (since 4.4.0).
  • Existing .resx files as vocabularies (Mafesoft.Localization.Resx, since 4.4.0).
  • Right-to-left languages: IsRightToLeft, TextDirection and the {culture:FlowDirection} markup extension for WPF and .NET MAUI (since 4.4.0).
  • Trimming and NativeAOT: the .NET 10 builds are IsTrimmable and IsAotCompatible (since 4.4.0).
  • Nullable reference types annotations, XML documentation, Source Link and symbols.

Comparison with the alternatives

Feature Mafesoft.Localization Microsoft.Extensions.Localization (ResX) LocalizationResourceManager.Maui WPFLocalizeExtension My.Extensions.Localization.Json
Culture change at runtime, bound UI refreshed ✅ WPF, MAUI, Blazor; per request on the server ⚠️ per request; Blazor reloads the page ✅ ✅ ⚠️ per request, no UI bindings
Translations from your own store (database, API) ✅ IVocabularyServiceProvider ⚠️ write your own IStringLocalizerFactory ⚠️ custom ResourceManager ✅ ILocalizationProvider ❌ JSON files only
Ready-made JSON files provider ✅ since 4.4.0 (Mafesoft.Localization.Json), reload on change ❌ ❌ ⚠️ write your own provider ✅
Missing keys reported ✅ AddOrUpdateTermAsync once per key, MissingTerm event, ILogger ⚠️ debug log, ResourceNotFound ❌ ✅ MissingKeyEvent ✅ log or throw
WPF, MAUI, MVC and Blazor with one API ✅ ⚠️ MVC and Blazor; no XAML markup ❌ MAUI only ❌ WPF only ❌ ASP.NET Core only
IStringLocalizer ✅ since 4.1.0 ✅ ❌ ❌ ✅
netstandard2.0 / .NET Framework 4.6.2+ ✅ ✅ ❌ net10.0 only ⚠️ .NET Framework only ❌ net10.0 only
Culture fallback (it-IT → it → neutral) ✅ since 4.3.0, opt-in (UseParentCultureFallback, FallbackCulture) ✅ ✅ ✅ ✅
Format arguments ✅ TranslateFormat(key, args) since 4.3.0, StringFormat, IStringLocalizer ✅ ✅ ⚠️ converter, not bindable ✅
Reuse existing .resx files ✅ since 4.4.0 (Mafesoft.Localization.Resx) ✅ ✅ ✅ ❌
Strongly typed keys ✅ since 4.4.0, generated from the JSON vocabularies, MLOC001 analyzer ⚠️ .resx designer class, not with IStringLocalizer ❌ ❌ ⚠️ GetString<T>(x => x.Prop)
Native AOT / trimming ✅ since 4.4.0 (.NET 10 builds; not with Newtonsoft.Json) ⚠️ abstractions only ⚠️ partly annotated ❌ ❌
Pluralization ❌ to evaluate (#33) ❌ ⚠️ zero/one only ❌ ❌
Design-time preview, non-string resources (images, sizes) ❌ ❌ ❌ ✅ ❌
Community, documentation, Q&A ❌ small ✅ part of .NET ⚠️ medium ⚠️ medium, last release 2023 ⚠️ medium

✅ built in, ⚠️ partial or extra work, ❌ not available. Checked in November 2026 against Microsoft.Extensions.Localization 11.0.0, LocalizationResourceManager.Maui 1.2.6, WPFLocalizeExtension 3.10.0 and My.Extensions.Localization.Json 4.1.0. The last rows list what the alternatives have and Mafesoft.Localization does not (or only partially), so that the comparison is not one-sided.

When to choose something else

  • .resx + IStringLocalizer (Microsoft.Extensions.Localization) when the translations ship with the build and change only with a new release: satellite assemblies, culture fallback, IViewLocalizer and the largest ecosystem.
  • LocalizationResourceManager.Maui for a MAUI-only app that already has .resx files and wants to switch the language at runtime.
  • WPFLocalizeExtension for a WPF-only app that needs the design-time preview or localizes images, sizes and other non-string properties.
  • My.Extensions.Localization.Json for an ASP.NET Core app that keeps the translations in JSON files next to the code and uses only IStringLocalizer.

Packages

Package Platform Target frameworks
Mafesoft.Localization
NuGet Downloads Mafe.Localization downloads
Core (any .NET application) .NET 10, .NET 8, .NET Standard 2.0, .NET Framework 4.6.2
Mafesoft.Localization.Extensions
NuGet Downloads
IStringLocalizer, dependency injection (since 4.1.0, see IStringLocalizer) .NET 10, .NET 8, .NET Standard 2.0
Mafesoft.Localization.Json
NuGet Downloads
JSON vocabularies and typed keys (since 4.4.0, see JSON vocabularies) .NET 10, .NET 8, .NET Standard 2.0, .NET Framework 4.6.2
Mafesoft.Localization.Json.Newtonsoft
NuGet Downloads
Newtonsoft.Json engine for the JSON vocabularies (since 4.4.0, see Choose the JSON engine) .NET 10, .NET 8, .NET Standard 2.0, .NET Framework 4.6.2
Mafesoft.Localization.Resx
NuGet Downloads
Vocabularies from existing .resx files (since 4.4.0, see Resx vocabularies) .NET 10, .NET 8, .NET Standard 2.0, .NET Framework 4.6.2
Mafesoft.Localization.Wpf
NuGet Downloads Mafe.Localization.Windows downloads
WPF net10.0-windows, net8.0-windows
Mafesoft.Localization.Maui
NuGet Downloads Mafe.Localization.Maui downloads
.NET MAUI .NET 10 (MAUI 10), .NET 8 (MAUI 8)
Mafesoft.Localization.Mvc
NuGet Downloads Mafe.Localization.Mvc downloads
ASP.NET Core MVC .NET 10, .NET 8
Mafesoft.Localization.Blazor
NuGet Downloads Mafe.Localization.Blazor downloads
Blazor Server, Blazor WebAssembly .NET 10, .NET 8
Mafesoft.Localization.Xamarin
NuGet Downloads Mafe.Localization.Xamarin downloads
Xamarin.Forms (deprecated, see Legacy) .NET Standard 2.0 / 2.1

The third badge, where present, counts the downloads of the old Mafe.Localization.* package, up to 3.0.0: Mafesoft.Localization.Wpf was published as Mafe.Localization.Windows, Mafesoft.Localization.Extensions is new in 4.1.0 and Mafesoft.Localization.Json, Mafesoft.Localization.Json.Newtonsoft and Mafesoft.Localization.Resx in 4.4.0.

  • .NET 10 (LTS, supported until November 2028) is the main target.
  • .NET 9 is not targeted: it reached end of support on 10 November 2026. .NET 9 applications use the .NET 8 build.
  • .NET 8 is out of support and is kept only for compatibility, so that existing .NET 8 applications can move to the Mafesoft.* packages without upgrading the runtime at the same time. It will be removed in a future major version.

Installation

Install the core package and the package for your technology:

dotnet add package Mafesoft.Localization
dotnet add package Mafesoft.Localization.Wpf      # or .Maui, .Mvc, .Blazor

The technology packages depend on Mafesoft.Localization, so for them the second command is enough. Add the package of the vocabularies if you do not write your own provider:

dotnet add package Mafesoft.Localization.Json     # JSON files (or .Resx for existing .resx files)

For IStringLocalizer and the dependency injection outside MVC and Blazor add Mafesoft.Localization.Extensions.

Quick start

  1. Write a provider that loads the vocabularies (here from memory; for JSON or .resx files use the ready-made providers, see JSON vocabularies and Resx vocabularies):

    using System.Globalization;
    using Mafesoft.Localization;
    
    public class InMemoryVocabularyServiceProvider : IVocabularyServiceProvider
    {
        private readonly Dictionary<string, Vocabulary> vocabularies = new()
        {
            ["it-IT"] = new Vocabulary { ["Hello"] = "Ciao", ["Welcome"] = "Benvenuto, {0}!" },
            ["en-US"] = new Vocabulary { ["Hello"] = "Hello", ["Welcome"] = "Welcome, {0}!" },
        };
    
        public Task InitializeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
    
        public Task<IVocabulary> LoadVocabularyAsync(CultureInfo cultureInfo, CancellationToken cancellationToken = default)
            => Task.FromResult<IVocabulary>(vocabularies.TryGetValue(cultureInfo.Name, out var vocabulary) ? vocabulary : new Vocabulary());
    
        public Task SaveAsync(IVocabulary vocabulary, CancellationToken cancellationToken = default) => Task.CompletedTask;
    
        public Task AddOrUpdateTermAsync(IVocabulary vocabulary, string key, string? defaultValue = null, CancellationToken cancellationToken = default)
        {
            Console.WriteLine($"Missing term: {key}");
            return Task.CompletedTask;
        }
    }
  2. Initialize the manager, translate and change the culture:

    await LocalizationManager.InitAsync(new InMemoryVocabularyServiceProvider(), new CultureInfo("it-IT"));
    
    Console.WriteLine(LocalizationManager.Translate("Hello"));                    // Ciao
    Console.WriteLine(LocalizationManager.Translate("Goodbye", "#Goodbye"));      // #Goodbye (and "Missing term: Goodbye")
    
    await LocalizationManager.Instance.SetCultureAsync(new CultureInfo("en-US"));
    Console.WriteLine(LocalizationManager.Translate("Hello"));                    // Hello
  3. Bind the texts of your UI: WPF, .NET MAUI, ASP.NET Core MVC, Blazor.

How it works

Localization Manager diagram

LocalizationManager.Instance is a process-wide singleton. It asks the provider for the vocabulary of the current culture and keeps it in memory. The platform packages bind the UI to the manager: when the culture changes, the manager raises PropertyChanged and CultureChanged, and every bound text is read again from the new vocabulary.

Server applications: because the manager is a singleton, in ASP.NET Core MVC and Blazor Server the selected culture is shared by all the users of the application, unless you set FollowCurrentUICulture (since 4.1.0, see Per-request culture on the server). In Blazor WebAssembly each user has their own.

Vocabulary service provider

A provider implements IVocabularyServiceProvider. Every method accepts a CancellationToken.

Method When it is called
InitializeAsync once, by Init / InitAsync (open a connection, read an index, warm a cache...)
LoadVocabularyAsync(culture) at initialization and at every culture change
SaveAsync(vocabulary) when you call LocalizationManager.Instance.SaveCultureAsync()
AddOrUpdateTermAsync(vocabulary, key) when a key is not in the vocabulary (for example to store it for the translators)

For JSON and .resx files there are ready-made providers, see JSON vocabularies and Resx vocabularies. Write your own for any other store. As an example, a minimal provider that reads one JSON file per culture (vocabularies/it-IT.json, vocabularies/en-US.json) looks like this:

using System.Globalization;
using System.Text.Json;
using Mafesoft.Localization;

public class FileVocabularyServiceProvider(string folder) : IVocabularyServiceProvider
{
    public Task InitializeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;

    public async Task<IVocabulary> LoadVocabularyAsync(CultureInfo cultureInfo, CancellationToken cancellationToken = default)
    {
        var path = Path.Combine(folder, $"{cultureInfo.Name}.json");
        if (!File.Exists(path))
        {
            return new Vocabulary();
        }

        await using var stream = File.OpenRead(path);
        var terms = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, cancellationToken: cancellationToken);
        return new Vocabulary(terms ?? new Dictionary<string, string>());
    }

    public async Task SaveAsync(IVocabulary vocabulary, CancellationToken cancellationToken = default)
    {
        var path = Path.Combine(folder, $"{LocalizationManager.CurrentCulture.Name}.json");
        await using var stream = File.Create(path);
        await JsonSerializer.SerializeAsync(stream, vocabulary, cancellationToken: cancellationToken);
    }

    public Task AddOrUpdateTermAsync(IVocabulary vocabulary, string key, string? defaultValue = null, CancellationToken cancellationToken = default)
    {
        // Add the missing key with an empty value: SaveCultureAsync() writes it to the file for the translators.
        vocabulary.TryAdd(key, string.Empty);
        return Task.CompletedTask;
    }
}

A term with an empty value counts as missing: Translate returns the default value.

Missing keys

Since 4.3.0. Each missing key is reported once per culture, not every time it is read: a key read 1 000 times in a list calls AddOrUpdateTermAsync once. The reported keys are forgotten when the culture changes (SetCulture, Init), so they are reported again for the new vocabulary.

// Diagnostics tooling: raised once per key and culture
LocalizationManager.Instance.MissingTerm += (sender, e) => Console.WriteLine($"{e.Culture.Name}: {e.Key}");

// Log the missing keys and the provider errors with ILogger instead of Trace
LocalizationManager.Instance.Logger = loggerFactory.CreateLogger<LocalizationManager>();

// Turn the reporting off (provider notification, event and log), for example in production
LocalizationManager.Instance.ReportMissingTerms = false;
  • AddMvcLocalizationManager, AddBlazorLocalizationManager, AddLocalizationManager (in an application with a host) and MAUI ConfigureLocalization(options => ...) set Logger from the ILoggerFactory of the application, so the missing keys appear in the ASP.NET Core / MAUI log (category Mafesoft.Localization.LocalizationManager, level Information; the provider errors are Warning).
  • Without a logger (WPF, .NET Framework, Blazor WebAssembly) they are written with System.Diagnostics.Trace.

JSON vocabularies

dotnet add package Mafesoft.Localization.Json

Since 4.4.0. Mafesoft.Localization.Json is a ready-made provider: one JSON file per culture, so you do not have to write an IVocabularyServiceProvider.

Resources/
  it-IT.json
  it.json
  en.json
{
  // flat or nested keys: "Home": { "Title" } is the key Home.Title
  "Hello": "Ciao",
  "Home": {
    "Title": "Benvenuto",
    "Menu": { "Open": "Apri" }
  }
}
using Mafesoft.Localization.Json;

// MAUI, WPF, Blazor WebAssembly: files embedded in the app (<EmbeddedResource Include="Resources\*.json" />)
var provider = JsonVocabularyServiceProvider.FromEmbeddedResources(typeof(App).Assembly, "Resources");

// ASP.NET Core: files on disk, reloaded when they change
var provider = JsonVocabularyServiceProvider.FromFileProvider(
    builder.Environment.ContentRootFileProvider, "Resources",
    new JsonVocabularyOptions { ReloadOnChange = true });

// Any directory
var provider = JsonVocabularyServiceProvider.FromDirectory(Path.Combine(AppContext.BaseDirectory, "Resources"));

await LocalizationManager.InitAsync(provider, new CultureInfo("it-IT"));
  • The file name is the culture name: it-IT.json, en.json, invariant.json for the invariant culture. A culture without a file has an empty vocabulary: with UseParentCultureFallback (see Culture fallback) it-IT reads the keys missing in it-IT.json from it.json.
  • Comments and trailing commas are allowed. Numbers and booleans are read as their text; arrays give one key per item (Days.0, Days.1). A file that is not valid JSON fails the load with an InvalidDataException naming the file.
  • ReloadOnChange (files only, not embedded resources): when a file is saved the LocalizationManager that uses the provider reloads its vocabularies (LocalizationManager.Instance.ReloadAsync()) and the bindings refresh. The Changed event of the provider is raised first. The reload runs on a thread pool thread.
  • MissingTermsDirectory: the keys used by the application and missing in a vocabulary are written to missing.<culture>.json in that directory, with their default value, ready to be translated and copied into the vocabulary. Meant for development.
  • The files are read with System.Text.Json (JsonDocument, no reflection) through IJsonVocabularySerializer: see Choose the JSON engine to use Newtonsoft.Json or another library.
  • The samples read their texts from samples/Localization.Samples.VocabularyServiceProvider/Resources: MAUI, WPF and Blazor WebAssembly as embedded resources, MVC and Blazor Server from the folder in development, so a saved change to a file shows up in the running app.

Typed keys

Since 4.4.0. Keys are strings: a typo is found only at runtime. Give the vocabularies to the compiler and Mafesoft.Localization.Json generates a class of constants, plus a warning for the keys that are not in the vocabulary:

<ItemGroup>
  <EmbeddedResource Include="Resources\*.json" />
  <AdditionalFiles Include="Resources\*.json" />
</ItemGroup>
// Generated in the root namespace of the project, from every vocabulary file:
// public static partial class Keys { public const string Home_Title = "Home.Title"; ... }
string title = LocalizationManager.Translate(Keys.Home_Title);
<!-- XAML (WPF, MAUI): xmlns:local is the namespace of the project -->
<Label Content="{culture:Translate ResourceKey={x:Static local:Keys.Home_Title}}" />
<h1>@Binding.Translate(Keys.Home_Title)</h1>
<translate key="@Keys.Home_Title"></translate>
  • Member names: Home.Title is Home_Title; other characters become _, a leading digit gets _ before it, a C# keyword gets @ (Keys.@class). The documentation of each constant shows its text in the reference vocabulary.
  • MLOC001 warns when a constant key passed to LocalizationManager.Translate, TranslateFormat or LocalizationManager.Instance[...] is not in the reference vocabulary: the file of MafesoftLocalizationDefaultCulture, otherwise invariant.json, otherwise the first file by name. Keys in XAML markup are not checked.
  • The vocabularies are the AdditionalFiles named after a culture (it-IT.json, en.json, invariant.json); missing.it-IT.json and other JSON files are ignored. MLOC002 reports a file that cannot be read.
  • MSBuild properties: MafesoftLocalizationKeysClass (default Keys), MafesoftLocalizationKeysNamespace (default the root namespace) and MafesoftLocalizationDefaultCulture (for example en).
<PropertyGroup>
  <MafesoftLocalizationDefaultCulture>en</MafesoftLocalizationDefaultCulture>
  <MafesoftLocalizationKeysClass>Texts</MafesoftLocalizationKeysClass>
</PropertyGroup>

Choose the JSON engine

The files are read with System.Text.Json by default: no extra dependency, safe with trimming and NativeAOT. An application that already uses Newtonsoft.Json can keep one JSON library:

dotnet add package Mafesoft.Localization.Json.Newtonsoft
using Mafesoft.Localization.Json.Newtonsoft;

var options = new JsonVocabularyOptions { ReloadOnChange = true }.UseNewtonsoftJson();        // default settings
var options = new JsonVocabularyOptions().UseNewtonsoftJson(mySerializerSettings);            // the application's settings
var options = new JsonVocabularyOptions { Serializer = new MyVocabularySerializer() };         // any other engine

var provider = JsonVocabularyServiceProvider.FromDirectory("Resources", options);
  • Both engines give the same keys and values for the same files (flat, nested, comments, arrays, numbers, booleans). Dates stay text with Newtonsoft.Json too; a number with an exponent (1e3) is read as 1000.
  • From the JsonSerializerSettings: MaxDepth when reading, Formatting and StringEscapeHandling when writing the missing terms file.
  • Newtonsoft.Json is not safe with trimming and NativeAOT: the warning comes only from that package, the main package does not depend on it.
  • Another engine implements IJsonVocabularySerializer: Read returns the terms of a file (nested keys joined with JsonVocabularyKeys.Separator), Write writes flat terms.

Resx vocabularies

dotnet add package Mafesoft.Localization.Resx

Since 4.4.0. An application that already has .resx files can adopt Mafesoft.Localization (XAML markup, runtime culture switch, missing-key reporting) without converting its resources:

using Mafesoft.Localization.Resx;

// Strings.resx, Strings.it.resx, Strings.it-IT.resx: the ResourceManager of the class generated by the designer
var provider = new ResxVocabularyServiceProvider(Strings.ResourceManager);
// or by type: new ResxVocabularyServiceProvider(typeof(Strings))

await LocalizationManager.InitAsync(provider, new CultureInfo("it-IT"));
  • The vocabulary of it-IT has the strings of Strings.it-IT.resx and, for the keys it does not have, of Strings.it.resx and Strings.resx: the same values as ResourceManager.GetString(key, culture).
  • Only string resources are read; images and other resources are skipped.
  • The .resx files are compiled into the application, so the provider does not save anything: see the missing keys with LocalizationManager.Instance.MissingTerm or the logger (see Missing keys).
  • The MVC sample reads Resources/SampleTexts.resx and SampleTexts.it.resx with "Vocabularies": "Resx" in appsettings.json.

LocalizationManager API

// Initialization (once, at startup). Without a culture the current UI culture is used.
LocalizationManager.Init(provider);
LocalizationManager.Init(provider, new CultureInfo("it-IT"));
await LocalizationManager.InitAsync(provider, new CultureInfo("it-IT"));

// Change the culture: the bindings are refreshed.
LocalizationManager.Instance.SetCulture(new CultureInfo("en-US"));
await LocalizationManager.Instance.SetCultureAsync(new CultureInfo("en-US"));
CultureInfo culture = LocalizationManager.CurrentCulture;

// Translate.
string text = LocalizationManager.Translate("Hello", "#Hello");   // never null: value, default value or key
string? value = LocalizationManager.Instance["Hello"];            // null when the key does not exist

// React to the culture change.
LocalizationManager.Instance.CultureChanged += (sender, e) => Console.WriteLine(LocalizationManager.CurrentCulture);

SetCultureAsync does not block the caller: use it from a UI thread (WPF, MAUI) when the provider is asynchronous.

// Since 4.1.0: read the vocabulary of a given culture, whatever the current culture is.
string english = LocalizationManager.Translate("Hello", new CultureInfo("en-US"), "#Hello");
string? value = LocalizationManager.Instance["Hello", new CultureInfo("en-US")];
IVocabulary vocabulary = await LocalizationManager.Instance.GetVocabularyAsync(new CultureInfo("en-US"));

The vocabularies are cached per culture: each culture is loaded from the provider once, also when many callers ask for it at the same time. SetCulture reloads the vocabulary of its culture, and Init clears the cache. Since 4.4.0. ReloadAsync() clears the cache and reloads the current culture, for example after the files of the provider changed.

Format arguments

Since 4.3.0. TranslateFormat translates a text with placeholders ("Welcome": "Hello {0}, you have {1} messages") and formats it with string.Format:

string text = LocalizationManager.TranslateFormat("Welcome", userName, count);

// With a default value: the arguments are an array, so a string argument is never taken as the default value
string text = LocalizationManager.TranslateFormat("Welcome", "Hello {0}, you have {1} messages", new object[] { userName, count });

// In the vocabulary of a given culture
string english = LocalizationManager.TranslateFormat("Welcome", new CultureInfo("en-US"), userName, count);
  • The arguments are formatted with the culture of the vocabulary (LocalizationManager.CurrentCulture, or the culture passed), not with the culture of the thread: 1.5 is 1,5 in an it-IT vocabulary.
  • When the key is missing the default value (or the key itself) is formatted.
  • A wrong format string ({name}, a missing argument, an unbalanced brace) does not throw: the text is returned unformatted and a warning is written.
  • The name is TranslateFormat and not Translate, because Translate("Welcome", userName) already means "userName is the default value".

Culture fallback

Since 4.3.0. By default a key that is not in the vocabulary of the culture returns the default value (or the key). Like ResX and IStringLocalizer, the manager can search the parent cultures first:

LocalizationManager.Instance.UseParentCultureFallback = true;            // it-IT → it → invariant
LocalizationManager.Instance.FallbackCulture = new CultureInfo("en");    // then en

// or at registration (AddLocalizationManager, AddMvcLocalizationManager, AddBlazorLocalizationManager)
builder.Services.AddMvcLocalizationManager(options =>
{
    options.ServiceProvider = JsonVocabularyServiceProvider.FromDirectory("vocabularies");
    options.UseParentCultureFallback = true;
    options.FallbackCulture = new CultureInfo("en");
});

The lookup order is: the culture (it-IT) → its parent cultures (it, then the invariant culture, with UseParentCultureFallback) → FallbackCulture → the default value → the key.

  • The provider is asked for the vocabulary of every culture of the chain: LoadVocabularyAsync(new CultureInfo("it")), LoadVocabularyAsync(CultureInfo.InvariantCulture) (Name is an empty string) and so on. Return an empty vocabulary for the cultures you do not have.
  • The vocabularies of the parent and fallback cultures are loaded only when a key is missing, and then cached like the others. A culture that fails to load is skipped.
  • The missing term is reported to the provider (AddOrUpdateTermAsync, with the vocabulary of the culture) only when no culture of the chain has the key. A term with an empty value counts as missing, so the chain goes on.
  • UseParentCultureFallback is false by default in 4.x, so the behavior does not change; FallbackCulture is null.
  • It applies to Translate, the indexers, the XAML markup extensions, the MVC and Blazor helpers and IStringLocalizer, also with FollowCurrentUICulture (the chain of the culture of the request).

Right-to-left languages

Since 4.4.0. When the culture changes to a right-to-left language (Arabic, Hebrew, Persian...) the layout direction can follow it, not only the text:

bool rtl = LocalizationManager.Instance.IsRightToLeft;        // CultureInfo.TextInfo.IsRightToLeft of the current culture
string dir = LocalizationManager.Instance.TextDirection;      // "rtl" or "ltr", for the HTML dir attribute

Both are notified with every culture change, like the translations.

<!-- WPF (xmlns:culture="clr-namespace:Mafesoft.Localization.Wpf;assembly=Mafesoft.Localization.Wpf") -->
<Window FlowDirection="{culture:FlowDirection}" ...>

<!-- .NET MAUI (xmlns:culture="clr-namespace:Mafesoft.Localization.Maui;assembly=Mafesoft.Localization.Maui") -->
<ContentPage FlowDirection="{culture:FlowDirection}" ...>
@* Blazor (App.razor) and MVC (_Layout.cshtml) *@
<html lang="@LocalizationManager.CurrentCulture.TwoLetterISOLanguageName" dir="@LocalizationManager.Instance.TextDirection">
  • With FollowCurrentUICulture (see Per-request culture on the server) the direction is the one of the culture of the request.
  • The samples switch between Italian, English and Arabic: WPF (combo box), MAUI (button) and Blazor Server (buttons); the Arabic texts are in samples/Localization.Samples.VocabularyServiceProvider/Resources/ar.json.

Per-request culture on the server

Since 4.1.0. By default LocalizationManager has one culture for the whole application: right for WPF, MAUI and Blazor WebAssembly, wrong on a server, where SetCulture would change the language of every user. On ASP.NET Core and Blazor Server set FollowCurrentUICulture: every lookup then uses CultureInfo.CurrentUICulture of the caller, which the request localization middleware sets for each request (and Blazor Server keeps for each circuit).

builder.Services.AddMvcLocalizationManager(options =>   // or AddBlazorLocalizationManager / AddLocalizationManager
{
    options.ServiceProvider = JsonVocabularyServiceProvider.FromDirectory("vocabularies");
    options.Culture = new CultureInfo("it-IT");          // loaded at startup
    options.FollowCurrentUICulture = true;
});

var app = builder.Build();

var cultures = new[] { "it-IT", "en-US" };
app.UseRequestLocalization(options => options
    .SetDefaultCulture(cultures[0])
    .AddSupportedCultures(cultures)
    .AddSupportedUICultures(cultures));   // before the endpoints that translate
  • Translate, the indexer, CurrentCulture, CurrentVocabulary, [Translate], the MVC helpers, Binding.Translate and IStringLocalizer follow the culture of the request.

  • The language is chosen by the request culture providers: query string (?culture=en-US&ui-culture=en-US), the culture cookie and Accept-Language. To let the user choose, write the cookie and redirect:

    app.MapGet("/culture/{culture}", (string culture, string redirectUri, HttpContext context) =>
    {
        context.Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)));
        return Results.LocalRedirect(redirectUri);
    });

    In Blazor Server the circuit keeps the culture of the request that opened it: after the redirect the page reloads and a new circuit starts with the new language.

  • Do not call SetCulture to switch the language of a user: with FollowCurrentUICulture it only reloads the vocabulary of that culture.

  • The first request in a culture loads its vocabulary. To load them at startup: foreach (var c in cultures) await LocalizationManager.Instance.GetVocabularyAsync(new CultureInfo(c));

WPF

dotnet add package Mafesoft.Localization.Wpf

Initialize the manager at startup (App.xaml.cs) with InitAsync, so a provider that reads from the network or a database does not block the UI thread:

protected override async void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    await LocalizationManager.InitAsync(JsonVocabularyServiceProvider.FromDirectory("vocabularies"), new CultureInfo("it-IT"));
}

The main window shows the default values until the vocabulary is loaded, then the bindings are refreshed. LocalizationManager.Init(...) is still available, but it blocks the caller until the vocabulary is loaded.

Translate in XAML:

xmlns:culture="clr-namespace:Mafesoft.Localization.Wpf;assembly=Mafesoft.Localization.Wpf"

<Label Content="{culture:Translate MainWindow, DefaultValue='Main Window'}" />
<TextBlock Text="{culture:Translate ChangedTimesTemplate, StringFormat='({0})'}" />

Or compute a value in code every time the culture changes (label is any FrameworkElement):

label.Translate(Label.ContentProperty, () => $"{LocalizationManager.Translate("Hello")} - {DateTime.Now:t}");

.NET MAUI

dotnet add package Mafesoft.Localization.Maui

Configure the manager in MauiProgram.cs:

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureLocalization(options =>
    {
        options.ServiceProvider = JsonVocabularyServiceProvider.FromEmbeddedResources(typeof(App).Assembly, "Resources");
        options.Culture = new CultureInfo("it-IT");
    });

Since 4.3.0 ConfigureLocalization(options => ...) does not block the startup (no risk of ANR on Android): the vocabulary is loaded asynchronously when the application is built, the controls show the default values until then and are refreshed when it is ready (CultureChanged). The overloads ConfigureLocalization(provider) and ConfigureLocalization(provider, culture) are kept for compatibility: they block until the vocabulary is loaded.

Translate in XAML:

xmlns:culture="clr-namespace:Mafesoft.Localization.Maui;assembly=Mafesoft.Localization.Maui"

<Label Text="{culture:Translate MainWindow, DefaultValue='Main Window'}" />

Or compute a value in code every time the culture changes (label is any BindableObject):

label.Translate(Label.TextProperty, () => LocalizationManager.Translate("Hello"));

ASP.NET Core MVC

dotnet add package Mafesoft.Localization.Mvc

Register the manager in Program.cs:

using Mafesoft.Localization.Mvc.Extensions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddMvcLocalizationManager(options =>
{
    options.ServiceProvider = JsonVocabularyServiceProvider.FromDirectory("vocabularies");
    options.Culture = new CultureInfo("it-IT");   // optional: the current UI culture by default
});

Since 4.3.0 AddMvcLocalizationManager (and AddBlazorLocalizationManager) does not call the provider: a hosted service initializes the manager asynchronously when the application starts (app.Run()), before the server accepts the first request. Code that runs between builder.Build() and app.Run() still sees the empty default vocabulary.

Annotate the view model with [Translate]:

using Mafesoft.Localization.Mvc;

public class PersonViewModel
{
    [Translate(ResourceKey = "NameText", DefaultValue = "#Name")]
    public string Name { get; set; } = "";

    [Translate("AddressText", "#Address")]
    public string Address { get; set; } = "";
}

The standard helpers use the translation (Html.LabelFor, <label asp-for>, Html.DisplayNameFor, validation messages), and the library adds two helpers:

@Html.TranslateLabelFor(m => m.Name)
@Html.TranslateLabel("Title", "TitleKey", "#Default title")

Since 4.3.0 two tag helpers translate directly in the views. Register them in _ViewImports.cshtml:

@addTagHelper *, Mafesoft.Localization.Mvc
<translate key="Home.Title" default="Welcome"></translate>   <!-- renders only the text -->
<button loc-key="Save">Save</button>                           <!-- replaces the content; kept when the key is missing -->

By default the culture is shared by all the users and changed with LocalizationManager.Instance.SetCulture(...). To give every user their own language set options.FollowCurrentUICulture = true and add app.UseRequestLocalization(...): see Per-request culture on the server.

Validation messages

Since 4.3.0 AddValidationMessageTranslation() translates the messages of the DataAnnotations attributes ([Required], [StringLength], [Range], [EmailAddress]...) that have no explicit message, on the server and in the data-val-* attributes of the client-side validation:

builder.Services.AddControllersWithViews()
    .AddValidationMessageTranslation();   // optional: o => o.KeyPrefix = "Errors."
Attribute Vocabulary key Example value
[Required] Validation.Required Il campo {0} è obbligatorio.
[StringLength(20)] Validation.StringLength Il campo {0} può avere al massimo {1} caratteri.
[StringLength(20, MinimumLength = 2)] Validation.StringLengthWithMinimum {0}: da {2} a {1} caratteri.
[Range(1, 10)] Validation.Range Il campo {0} deve essere tra {1} e {2}.
  • The key is the prefix (Validation. by default) followed by the attribute name without Attribute; {0} is the display name of the property (translated with [Translate]), the other placeholders are the arguments of the attribute.
  • When the key is missing the default English message is used (and the key is reported to the provider).
  • An attribute with ErrorMessage or ErrorMessageResourceType is not changed; with AddDataAnnotationsLocalization() its message still goes to your IStringLocalizer (for example the one of IStringLocalizer).
  • It works with AddMvcLocalizationManager and with AddLocalizationManager(...).AddStringLocalizer().

Blazor

dotnet add package Mafesoft.Localization.Blazor

Blazor Web App (interactive server): register the manager in Program.cs.

using Mafesoft.Localization.Blazor.Extensions;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
builder.Services.AddBlazorLocalizationManager(options =>
{
    options.ServiceProvider = JsonVocabularyServiceProvider.FromDirectory("vocabularies");
    options.Culture = new CultureInfo("it-IT");
    options.FollowCurrentUICulture = true;   // since 4.1.0: one language per circuit, with app.UseRequestLocalization(...)
});

With FollowCurrentUICulture every circuit uses the culture of the request that opened it (see Per-request culture on the server); without it the culture is shared by all the users and changed with SetCulture.

Blazor WebAssembly: the package does not depend on the ASP.NET Core shared framework, so it runs in the browser too. Initialize the manager asynchronously: a provider that loads the vocabularies with HttpClient cannot be waited synchronously on the single WebAssembly thread. The WebAssembly host does not run hosted services: there AddBlazorLocalizationManager starts the initialization in the background (the default values are shown until the vocabulary is loaded); to wait for it, call InitAsync before RunAsync():

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

await LocalizationManager.InitAsync(new InMemoryVocabularyServiceProvider(), new CultureInfo("it-IT"));
builder.Services.AddSingleton(LocalizationManager.Instance);

await builder.Build().RunAsync();

Since 4.3.0 the <Translate> component is the shortest way: it renders the translation and renders again by itself when the culture changes, with no CultureChanged subscription in the page.

@using Mafesoft.Localization.Blazor.Components   @* or in _Imports.razor *@

<h1><Translate Key="Home.Title" Default="Welcome" /></h1>
<p><Translate Key="Greeting" Default="Hello {0}" Args="new object[] { userName }" /></p>

Args formats the text with the culture of the vocabulary (see Format arguments).

Or translate in a component with Binding.Translate, and refresh the component when the culture changes:

@using Mafesoft.Localization.Blazor.Bindings
@implements IDisposable

<h1>@Binding.Translate("BlazorCounter", "#Counter")</h1>
<p>@Binding.Translate("ChangedTimesTemplate", stringFormat: "({0})")</p>

@code {
    protected override void OnInitialized() => LocalizationManager.Instance.CultureChanged += OnCultureChanged;
    private void OnCultureChanged(object? sender, EventArgs e) => InvokeAsync(StateHasChanged);
    public void Dispose() => LocalizationManager.Instance.CultureChanged -= OnCultureChanged;
}

The samples samples/Localization.Samples.AppBlazor (Blazor Web App) and samples/Localization.Samples.AppBlazorWasm (Blazor WebAssembly) show both models.

IStringLocalizer

dotnet add package Mafesoft.Localization.Extensions

Since 4.1.0. The Mafesoft.Localization.Extensions package plugs the vocabularies into Microsoft.Extensions.Localization: IStringLocalizer, IStringLocalizer<T> and IStringLocalizerFactory read the vocabulary of the current culture, so DataAnnotations, IViewLocalizer, Blazor components and third-party libraries use the same translations.

using Mafesoft.Localization.Extensions;

builder.Services.AddLocalizationManager(options =>
{
    options.ServiceProvider = JsonVocabularyServiceProvider.FromDirectory("vocabularies");
    options.Culture = new CultureInfo("it-IT");
    options.InitializeOnHostStart = true;   // since 4.3.0: load the vocabulary asynchronously when the host starts
})
.AddStringLocalizer();

// ASP.NET Core MVC: [Display(Name = "...")] and the validation messages are translated too
builder.Services.AddControllersWithViews().AddDataAnnotationsLocalization();

AddLocalizationManager initializes the manager synchronously by default, so it also works with a plain ServiceCollection without a host. With InitializeOnHostStart = true (since 4.3.0) it does not call the provider: a hosted service loads the vocabulary asynchronously when the host starts.

public class HomeController(IStringLocalizer<HomeController> localizer) : Controller
{
    public IActionResult Index() => View(model: localizer["Welcome"].Value);
}
  • A missing key returns the key itself with ResourceNotFound = true, and the provider is notified (AddOrUpdateTermAsync), like LocalizationManager.Instance[key].
  • localizer["Format", arg] formats the value with the current culture; GetAllStrings() returns the current vocabulary.
  • By default every localizer reads the same keys. With .AddStringLocalizer(o => o.UseTypeNamePrefix = true) the keys are prefixed with the type name: IStringLocalizer<HomeController>["Title"] reads HomeController.Title.
  • AddStringLocalizer() replaces an IStringLocalizerFactory registered before, for example by AddLocalization().
  • On a server set options.FollowCurrentUICulture = true and add app.UseRequestLocalization(...), so the localizers follow the culture of each request (see Per-request culture on the server). The package README lists the differences from the resx localizer.

Trimming and NativeAOT

Since 4.4.0. The .NET 10 builds of the packages are marked trimmable and AOT compatible (IsTrimmable, IsAotCompatible): an app published with trimming or NativeAOT (iOS, Mac Catalyst, Android, console, ASP.NET Core minimal APIs) gets no trimming / AOT warnings from the Mafesoft assemblies.

  • MAUI: {culture:Translate}, {culture:FlowDirection} and Translate(...) in code create typed bindings (a getter, as compiled XAML bindings do) instead of string-path bindings, which MAUI reports as not trim safe.
  • Mafesoft.Localization.Json reads the files with JsonDocument (no reflection). Mafesoft.Localization.Json.Newtonsoft is the exception: Newtonsoft.Json is not trim safe, use the default engine in trimmed apps.
  • WPF and ASP.NET Core MVC do not support trimming themselves; the packages add no warnings of their own.
  • CI publishes samples/Localization.Samples.AotCheck with NativeAOT (every trimming / AOT warning is an error) and runs it, and publishes the MAUI sample with NativeAOT for Mac Catalyst.

Migrating from Mafe.Localization

4.0.0 is a breaking release for every consumer: it renames the packages and the namespaces, and fixes the naming of the public API in the same release, so that you migrate only once. The Mafe.Localization* packages are deprecated on NuGet.org and point to the new Mafesoft.* packages.

1. Packages (#12)

3.x package 4.0.0 package
Mafe.Localization Mafesoft.Localization
Mafe.Localization.Maui Mafesoft.Localization.Maui
Mafe.Localization.Mvc Mafesoft.Localization.Mvc
Mafe.Localization.Blazor Mafesoft.Localization.Blazor
Mafe.Localization.Windows Mafesoft.Localization.Wpf
Mafe.Localization.Xamarin Mafesoft.Localization.Xamarin (last release, deprecated)

2. Namespaces (in Razor, update _ViewImports.cshtml and _Imports.razor too)

3.x namespace 4.0.0 namespace
Localization Mafesoft.Localization
Localization.Providers Mafesoft.Localization.Providers
Localization.Maui.* Mafesoft.Localization.Maui.*
Localization.Maui.Converts Mafesoft.Localization.Maui.Converters
Localization.Mvc.* Mafesoft.Localization.Mvc.*
Localization.Blazor.* Mafesoft.Localization.Blazor.*
Localization.Windows.* Mafesoft.Localization.Wpf.*
Localization.Xamarin.* Mafesoft.Localization.Xamarin.*
Localization.Xamarin.Converts Mafesoft.Localization.Xamarin.Converters

3. XAML namespaces

<!-- MAUI -->
xmlns:culture="clr-namespace:Localization.Maui;assembly=Mafe.Localization.Maui"                 <!-- 3.x -->
xmlns:culture="clr-namespace:Mafesoft.Localization.Maui;assembly=Mafesoft.Localization.Maui"    <!-- 4.0 -->

<!-- WPF -->
xmlns:culture="clr-namespace:Localization.Windows;assembly=Mafe.Localization.Windows"           <!-- 3.x -->
xmlns:culture="clr-namespace:Mafesoft.Localization.Wpf;assembly=Mafesoft.Localization.Wpf"      <!-- 4.0 -->

4. Public API (#15)

3.x 4.0.0
IVocabolary, Vocabolary IVocabulary, Vocabulary
IVocabolaryServiceProvider IVocabularyServiceProvider
Initialize() InitializeAsync(CancellationToken cancellationToken = default)
LoadVocabolaryAsync(CultureInfo) LoadVocabularyAsync(CultureInfo, CancellationToken cancellationToken = default)
SaveAsync(IVocabolary) SaveAsync(IVocabulary, CancellationToken cancellationToken = default)
AddOrUpdateTermAsync(vocabolary, key, defaultValue) AddOrUpdateTermAsync(vocabulary, key, defaultValue, CancellationToken cancellationToken = default)
IBinding.ConverterParamenter (Blazor) IBinding.ConverterParameter

A custom provider must rename Initialize to InitializeAsync and add the CancellationToken parameter to every method. LocalizationManager.InitAsync, SetCultureAsync, LoadOrUpdateCultureAsync and SaveCultureAsync also accept an optional CancellationToken, which is passed to the provider.

The API is annotated for nullable reference types: the indexer LocalizationManager.Instance[key] returns string?, Translate returns string (#17).

5. Target frameworks (#14)

  • .NET 9 targets removed: .NET 9 applications use the .NET 8 build.
  • Core: the .NET Framework 4.7.2 / 4.8 and .NET Standard 2.1 builds are removed; those applications use the .NET Framework 4.6.2 and .NET Standard 2.0 builds.

The full list of changes is in the CHANGELOG.

Legacy: Xamarin.Forms

⚠️ Mafesoft.Localization.Xamarin 4.0.0 is the last release of the Xamarin package and it is deprecated: Xamarin.Forms has been out of support since May 1, 2024. It will receive no further updates or fixes. Use it only to align with the Mafesoft.* packages while you migrate to .NET MAUI.

It works like the MAUI package (LocalizationManager.Init(...) at startup, then {culture:Translate ...} in XAML with xmlns:culture="clr-namespace:Mafesoft.Localization.Xamarin;assembly=Mafesoft.Localization.Xamarin").

To migrate to .NET MAUI, replace the package with Mafesoft.Localization.Maui, configure it with ConfigureLocalization(...) and change the XAML namespace to clr-namespace:Mafesoft.Localization.Maui;assembly=Mafesoft.Localization.Maui: the markup extension is the same.

Build and test

dotnet build src/Localization.sln
dotnet test src/Localization.Tests
dotnet test src/Localization.Maui.Tests
dotnet test src/Localization.Wpf.Tests     # Windows only

Localization.Tests (core, MVC, Blazor, IStringLocalizer, JSON and Resx vocabularies, typed keys generator, right-to-left) runs on .NET 8 and .NET 10, and on Windows also on .NET Framework (the core tests against the net462 build); Localization.Maui.Tests runs the MAUI controls without a platform head on .NET 10 (Linux, macOS and Windows); Localization.Wpf.Tests runs on .NET 10 on Windows. The samples (samples/Localization.Samples.sln: WPF, MAUI, MVC, Blazor Web App, Blazor WebAssembly, Xamarin, and the AotCheck console app) reference the projects inside src, so they always run with the current code.

The CI (.github/workflows/ci.yml) runs on Ubuntu and Windows, publishes the code coverage in the job summary and, on Windows, builds the samples (MAUI with dotnet workload restore, Windows head only; Xamarin is not built). It also publishes Localization.Samples.AotCheck with NativeAOT and the MAUI sample for Mac Catalyst (see Trimming and NativeAOT).

global.json pins the .NET 10 SDK (any newer feature band is accepted). The package versions of the projects in src are defined in one place, src/Directory.Packages.props (Central Package Management); src/nuget.config restores them from nuget.org only. .editorconfig holds the code style.

Release

All the packages share one version, <VersionPrefix> in src/Directory.Build.props. To publish a release:

  1. update <VersionPrefix> and the CHANGELOG (a ## [x.y.z] - date section);
  2. push the tag v<version> (e.g. v4.4.0, or v4.4.0-beta.1 for a prerelease).

The NuGet workflow (.github/workflows/nuget.yml) runs only for v* tags: it fails if the tag does not match <VersionPrefix>, then tests, packs and publishes all the packages with the same version, and creates the GitHub Release of the tag with the packages attached and the notes of the matching CHANGELOG section. A release created by hand on GitHub works too: the workflow attaches the packages to it. Merging to main publishes nothing. A manual run of the workflow (workflow_dispatch) with an empty version is a dry run: it tests and packs without publishing.

Every dotnet pack runs the package validation: inside a major version the package is compared with the first release of that version (4.1.0 with 4.0.0), so a breaking API change in a minor or patch version fails the pack. A package first published in a minor version sets <PackageFirstVersion> in its .csproj (see src/Directory.Build.targets).

The workflow publishes with NuGet trusted publishing, with no long-lived API key: the publish job runs in the production environment, the NUGET_USER secret holds the nuget.org user name and nuget.org has a trusted publishing policy for owner fmazzant, repository Localization, workflow file nuget.yml and environment production (renaming the file breaks publishing).

Contributing

Bug reports, ideas and pull requests are welcome.

  1. Open an issue that describes the bug or the change.
  2. Create a branch from main named after the issue (for example feat/42-short-description).
  3. Keep the change focused, add or update the tests, and make sure dotnet build (no warnings: nullable warnings are errors) and dotnet test pass.
  4. Update the README and add an entry to the Unreleased section of the CHANGELOG.
  5. Open a pull request that references the issue (Fixes #42).

Security problems must not be reported in public issues: see the security policy.

Support

If Mafesoft.Localization saves you time, you can say thanks with a small donation. It is never required, but it helps me keep the project maintained and up to date.

Donate

A star on GitHub, a bug report or a pull request help too. Thank you!

License

Mafesoft.Localization is released under the MIT License.

About

A library for .NET that can help you to manage the localization in your application. The library includes Wpf extension, Xamarin extension, MAUI extension and Mvc extension.

Topics

Resources

Security policy

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages