Localize.Core
1.2.0
See the version list below for details.
dotnet add package Localize.Core --version 1.2.0
NuGet\Install-Package Localize.Core -Version 1.2.0
<PackageReference Include="Localize.Core" Version="1.2.0" />
<PackageVersion Include="Localize.Core" Version="1.2.0" />
<PackageReference Include="Localize.Core" />
paket add Localize.Core --version 1.2.0
#r "nuget: Localize.Core, 1.2.0"
#:package Localize.Core@1.2.0
#addin nuget:?package=Localize.Core&version=1.2.0
#tool nuget:?package=Localize.Core&version=1.2.0
<img src="https://github.com/gordon-matt/Localize.NET/raw/master/_Misc/Logo.png" alt="Logo" width="350" />
Database, JSON, and RESX translations behind one IStringLocalizer, with a Blazor admin built on NetForge.
A string is resolved from the request culture, then each parent culture, then the invariant text. Within one culture the sources are merged by priority. A higher number wins:
| Source | Priority | Writes |
|---|---|---|
Language packs (ILanguagePack) |
10 | No |
| RESX | 40 | No |
| JSON files | 50 | No |
| Database | 100 | Yes, from the admin |
RESX, JSON, and language packs are read-only inputs to the catalog. Saving in the string editor writes a database row. Registering a database leaves the other sources in place. They keep supplying a string until a row exists for that key and culture.
External is separate. It edits JSON files in a folder you point at, and those strings are not read by IStringLocalizer. Adding the folder copies the current text into ExternalStrings so Reset can write it back.
A row is written when someone saves in the editor, imports a file, or resets the scope to its language packs. TrackMissingKeys also writes one, for a key that no source had, and stores the key itself as the invariant text. Once that row exists, the stored text is what the localizer returns. Editing the RESX or JSON file has no effect on that key. Delete the row and the file is used again.
Set Localize:JsonOverridesDatabase when a deployed file should beat a stored row.
The invariant culture is stored as an empty culture code. A missing translation falls through.
Screenshots
<img src="https://github.com/gordon-matt/Localize.NET/blob/master/_Misc/Screenshots/Languages.png" alt="Languages" />
<img src="https://github.com/gordon-matt/Localize.NET/blob/master/_Misc/Screenshots/Strings.png" alt="Strings" />
<img src="https://github.com/gordon-matt/Localize.NET/blob/master/_Misc/Screenshots/Demo_English.png" alt="Demo - English" />
<img src="https://github.com/gordon-matt/Localize.NET/blob/master/_Misc/Screenshots/Demo_French.png" alt="Demo - French" />
Add it to a site
The localizer and the admin are separate packages. A class library or another Razor class library references Localize.Core when it ships an ILanguagePack or a display-name attribute, and injects IStringLocalizer from Microsoft.Extensions.Localization. It does not reference Localize.Components. The host is the only project that takes the admin. The editor manages the host's strings and the strings from referenced libraries. A saved row overrides the library text.
builder.Services.AddLocalize(options =>
{
options.JsonDirectory = "Localization";
options.TrackMissingKeys = true; // store a key the first time a page asks for it
});
builder.Services.AddLocalizeSqlite(); // or AddLocalizeSqlServer / AddLocalizeNpgsql / AddLocalizeMySql
AddLocalize() and AddLocalize(isLibrary: false) register the host catalog and replace IStringLocalizer. Call either one and the database method in either order. JSON, RESX, and language packs still resolve when no database is registered. ILanguageService and the editor need one. Migrations run on startup (AutoMigrate) and, for the global scope, DefaultCulture (en-US) is inserted as an enabled language. Library packs are picked up without the host naming each class. How they are found depends on whether the host uses Dependo. See Finding library packs.
Inside a library, mark the invariant pack and call AddLocalize(isLibrary: true). That call leaves a localizer the host already registered. The catalog localizer still reads this pack. Either localizer returns the invariant text from the indexer, so a host that never registers the catalog still sees English.
services.AddLocalize(isLibrary: true);
[LocalizePack]
public sealed class MessagingLanguagePack : ILanguagePack
{
public string? CultureCode => null;
public IDictionary<string, string> LocalizedStrings { get; } = new Dictionary<string, string>
{
["Messaging/Inbox.Title"] = "Inbox",
};
}
public sealed class Inbox(IStringLocalizer T)
{
public string Title => T["Messaging/Inbox.Title"];
}
Prefix a library's keys with its name so they sit beside the host's keys in the editor. Saving writes a database row for the current scope, and that row is what the library's localizer returns.
Admin
Reference Localize.Components from the host only.
builder.Services.AddLocalizeComponents();
app.UseLocalize();
app.MapLocalize(); // culture cookie and JSON export
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddAdditionalAssemblies(typeof(Localize.Components.Pages.Languages).Assembly);
Point ForgeRouter.AdditionalAssemblies at the same assembly. Drop the link in with AddLocalize() on a menu group, or IncludeRegistered(), which files it under Settings.
Routes:
/localize/languages/localize/strings/{cultureCode}/localize/external/localize/external/{folderId}/localize/external/{folderId}/{cultureCode}
Multi-tenant scope
Language, LocalizableString, and LocalizableProperty are partitioned by a string scope. A single-tenant site leaves it empty.
builder.Services.AddLocalize<TenantLocalizationScope>(options => options.TrackMissingKeys = true);
public sealed class TenantLocalizationScope(IWorkContext work) : ILocalizationScope
{
public string? GetScopeId() => work.CurrentTenant?.Id.ToString();
}
Call ILanguageService.EnsureDefaultAsync() when a tenant is created. The startup seed only covers the global scope.
Language packs
CultureCode null is the invariant pack. [LocalizePack] is enough for a referenced library. The host can still register a pack that needs configuration:
builder.Services.AddSingleton<ILanguagePack, HostLanguagePack>();
[LocalizePack]
public sealed class MyLanguagePack : ILanguagePack
{
public string? CultureCode => null;
public IDictionary<string, string> LocalizedStrings { get; } = new Dictionary<string, string>
{
["App/Home.Title"] = "Home",
};
}
A pack that cannot be constructed with a public parameterless constructor registers itself when its assembly loads:
internal static class MessagingLocalization
{
[ModuleInitializer]
internal static void Register() => LocalizePacks.Add(new MessagingLanguagePack());
}
LocalizePacks.Add(cultureCode, strings) does the same without a class. T["App/Home.Title"] reads that text until an editor, a JSON file, or a RESX overrides it. T["App/Home.Greeting", name] formats with the current UI culture. The string editor lists every key those sources know, including keys from referenced packages, and saving writes a database override for the current scope. Reset on the languages page deletes the scope's stored strings and inserts the packs again. The files stay on disk, but the new rows win over RESX and JSON for those keys. A host registration of the same pack class is kept, and its text wins over the discovered instance.
Finding library packs
A library marks its invariant pack with [LocalizePack] and calls AddLocalize(isLibrary: true) from its own registration. That call leaves an IStringLocalizer the host already registered. AddLocalize() and AddLocalize(isLibrary: false) replace it with the catalog localizer. Either one returns the invariant text from T["Key"], so a host that never registers the catalog still sees English. DiscoverLibraryPacks turns discovery off and leaves only packs the host registered itself.
The library class is the same for both hosts. It needs a public parameterless constructor. A pack that needs services calls LocalizePacks.Add from a module initializer instead.
Host without Dependo
DependoCatalog is not sealed, so TryGetExports does not answer. Localize reads assemblies that are already loaded and that reference Localize.Core. Every concrete class marked with [LocalizePack] is constructed. An assembly loaded later, such as a plugin the host loads itself, is read when it loads. Localize does not walk the dependency graph or call Assembly.Load.
A referenced library is found once something has loaded its assembly. Calling one of its types, or calling its Add* method, is enough. A package that nothing has touched yet is not opened just to look for packs.
Host with Dependo
Localize.Core is marked [assembly: DependoExports(typeof(ILanguagePack))]. The host's Dependo generator registers that service and seals the catalog when the entry assembly loads. It also loads the assemblies that published exports. Localize then calls DependoCatalog.TryGetExports and constructs each concrete ILanguagePack. Assemblies loaded after startup are picked up by the catalog on the next read. Localize does not load them itself.
Dependo returns every concrete ILanguagePack, including one that is not marked with [LocalizePack]. A class without a public parameterless constructor is skipped. Register that one with LocalizePacks.Add or AddSingleton<ILanguagePack, ...>.
JSON
Localize:JsonDirectory is relative to the content root.
Localization/fr-FR.jsonorLocalization/fr-FR/Home.jsonis French. Nested objects flatten with dots (Home.Title).default.jsonorinvariant.jsonis the invariant culture.- A file named
Home.jsonin the root of that folder is ignored, so a stray JSON file is not treated as a culture. - The admin import accepts a flat dictionary, nested objects, or
{ "cultureCode", "localizedStrings" }. A culture the file introduces is added switched off.
External files
A folder of JSON that some other library already loads can be edited without copying those strings into the catalog. The Languages page has an External button. Enter the folder and give it a name. The path is relative to the content root unless it is a full path. Home on that page returns to Languages.
A file is included when its name or its parent folder is a culture .NET knows, such as fr, fr-FR, or zh-Hans. fr.json and fr/translations.json are French. default.json is the default language. A name .NET does not know, such as package.json or xx.json, is skipped and left on disk. If none of the JSON files name a known culture, the folder is not added. Nested objects stay nested. A property whose name contains a dot stays one key. The key shown in the editor joins the property names with dots.
The editor lists every key found in any file. A language that has no value for a key shows a blank row. Saving writes that key into the file for that language, creating the file when the folder already uses that pattern for another language. Clearing the text removes the key. File names and folders are left as they are. Saving rewrites that one file as indented JSON. The other files are not rewritten.
Each other language is shown beside a default language for that folder. The Default language button on the folder list opens a drawer and stores the choice. Until one is chosen, the editor prefers a file named en, then en-US, then default.json. When none of those exist, it uses the culture whose files currently have the most keys. Equal counts use the culture name. A library that ships no English file, because English is built in, can still be compared by choosing one of the files that is there.
That works when the files are ordinary JSON. DataTables language files are JSON, so External files can edit them. TinyMCE language packs are not. They are JavaScript in a form that belongs to TinyMCE, and this editor does not read them. For a library like that, the demo only loads the pack that matches the culture selected in Localize. The DataTables demo page does the same with the JSON file for the selected culture, and that folder can also be edited here.
Adding the folder copies each value into ExternalStrings, and the folder into ExternalFolders. That copy is the default. Reset writes it back and deletes culture files that were not in the folder then. A file that already matches the copy is left byte for byte. Removing the folder deletes the copy and leaves the files on disk. The copy is taken once, when the folder is added. A later edit changes the file and leaves the copy alone.
These strings are not part of IStringLocalizer, and they are not the Localize:JsonDirectory catalog. The folder list is stored per scope, the same way languages are. The files themselves are the ones on disk, shared by every scope that points at them.
The demo registers three folders, and French is missing a few keys so the blank rows are visible:
wwwroot/lib/greet—en.json,fr.json,de.jsonwwwroot/lib/shop—en/translations.json,fr/translations.json,de/translations.jsonwwwroot/js/calendar—en-US.json,fr-FR.json,de-DE.json, with nested objects
RESX
builder.Services.AddLocalizeResx<SharedResources>();
The type needs the generated public static ResourceManager. RESX is read-only. Parent cultures are not applied twice; the catalog walks them.
Entity fields
UI strings and translated entity fields are different tables. The entity keeps the invariant value. A row in LocalizableProperties replaces one property for one culture.
string? title = await properties.ValueOrDefaultAsync(
cultureCode, typeof(Page).FullName!, page.Id.ToString(), "Title", page.Title);
FindAsync loads a batch. DeleteForEntityAsync removes every culture when the entity is deleted. Scope is included, so two tenants with the same entity id do not collide.
LocalizedDisplayNameAttribute and LocalizedHelpTextAttribute take a catalog key. They resolve IStringLocalizer once the host has started.
Options
Bound from the Localize section.
| Option | Default | |
|---|---|---|
DefaultCulture |
en-US |
Used when the visitor has not chosen, and seeded as a language |
CultureCookieName |
CurrentCulture |
|
UseParentCultureFallback |
true | fr-FR then fr then invariant |
TrackMissingKeys |
false | Store a missing key the first time a page asks for it. That row then wins over a file added later |
JsonDirectory |
empty | No JSON until this is set |
JsonOverridesDatabase |
false | |
AutoMigrate |
true | |
SeedDefaultLanguage |
true | Global scope only |
RequireAuthentication |
true | Admin pages. The culture switch stays public |
ManagePolicy |
empty | Authorization policy for the admin pages. Empty allows any signed-in user when authentication is required |
ImportOnlyKnownKeys |
false | When true, import will not create keys that have no invariant row |
DiscoverLibraryPacks |
true | Read [LocalizePack] classes. A Dependo host uses its catalog instead of a separate assembly walk |
Layout
Localize.Core has no database and no UI. Packs and scopes reference that. Localize.Services is the catalog and the localizer. Localize.Data holds the mappings. Localize.Data.Sql, .Npgsql, .MySql, and .Sqlite hold the provider, the migrations, and the AddLocalize* method. Repositories are bound to ILocalizeDbContextFactory so they do not take over the host's IDbContextFactory. Localize.Components is the Razor class library. Localize.Demo is a small host that shows the switcher and the admin.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Dependo (>= 1.3.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Localization.Abstractions (>= 10.0.14)
- System.Security.Cryptography.Pkcs (>= 10.0.14)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Localize.Core:
| Package | Downloads |
|---|---|
|
IdentityNexus.Services
Services for administering an ASP.NET Core Identity store. |
|
|
Localize.Data
Provider-agnostic data model for Localize. Tables live in the localize schema. |
|
|
Localize.Services
String catalog, localizer and storage services for Localize. |
GitHub repositories
This package is not used by any popular GitHub repositories.