How would you serve ASP.NET Core localized strings from a database instead of .resx, and what contract must the IStringLocalizer implementation keep?
answer
- replace the factory, not every consumer
- per resource, not per culture
- read CurrentUICulture on every lookup
- return the key with ResourceNotFound
- singleton factory: no scoped DbContext
basics
~20 sImplement IStringLocalizerFactory and IStringLocalizer over the store and register the factory as the singleton IStringLocalizerFactory. Each localizer is per resource, reads CurrentUICulture on every lookup, never throws for a missing key, and serves from a cache, not a query per string.
solid answer
~40 sEvery localizer in ASP.NET Core goes through `IStringLocalizerFactory`: `StringLocalizer<T>` calls `Create(typeof(T))`, `HtmlLocalizerFactory` and `IViewLocalizer` call it, and MVC's DataAnnotations localization does too. So you write a factory with `Create(Type)` and `Create(string baseName, string location)`, and an `IStringLocalizer` with both indexers and `GetAllStrings`, then register the factory as a singleton; `AddLocalization` uses `TryAdd` and keeps it. The contract: a localizer is per resource, not per culture (`WithCulture` was removed in ASP.NET Core 5.0), so it reads `CultureInfo.CurrentUICulture` on each lookup and walks to parent cultures; a miss returns `new LocalizedString(name, name, resourceNotFound: true)`; arguments are formatted with `CurrentCulture`; and it is thread-safe. The indexers are synchronous and the factory is a singleton, so load translations into an in-memory snapshot rather than querying a scoped `DbContext` per string.
code
csharp · 22 linespublic sealed class DbStringLocalizer(string resource, ITranslationSnapshot snapshot) : IStringLocalizer
{
public LocalizedString this[string name] => Lookup(name, null);
public LocalizedString this[string name, params object[] arguments] => Lookup(name, arguments);
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures) =>
snapshot.Keys(resource, CultureInfo.CurrentUICulture, includeParentCultures).Select(k => this[k]);
private LocalizedString Lookup(string name, object[]? args)
{
string? format = null;
for (var c = CultureInfo.CurrentUICulture; format is null; c = c.Parent)
{
snapshot.TryGet(resource, c.Name, name, out format);
if (c.Equals(CultureInfo.InvariantCulture)) break;
}
var value = args is null ? format ?? name
: string.Format(CultureInfo.CurrentCulture, format ?? name, args);
return new LocalizedString(name, value, resourceNotFound: format is null, searchedLocation: resource);
}
}go deeper
Recall that IStringLocalizer is an interface, so .resx is only the default store, and that a missing key must return the key.
Explain which two interfaces to implement, why replacing the factory changes every localizer type, and how registration interacts with TryAdd.
Design the store for production: an in-memory snapshot with atomic refresh, no scoped DbContext in a singleton, parent-culture fallback, and visible tracking of misses.
Weigh a database or translation-service store against .resx in source control: who edits translations, how changes are reviewed and released, and the cost of a runtime dependency on the store.
## Why one replacement is enough `.resx` is only the default store. Everything above it talks to one abstraction: - `StringLocalizer<T>`, the implementation behind `IStringLocalizer<T>`, calls `factory.Create(typeof(T))` in its constructor; - `HtmlLocalizerFactory` wraps `IStringLocalizerFactory`, so `IHtmlLocalizer<T>` and `IViewLocalizer` use it, the latter through `Create(baseName, location)` with a base name built from the view path; - MVC's DataAnnotations localization calls the factory through `DataAnnotationLocalizerProvider`. Replace `IStringLocalizerFactory` and the whole stack reads your store, with no change to controllers, views or models. ## The two interfaces | Member | What it must do | |---|---| | `IStringLocalizerFactory.Create(Type)` | return a localizer for the resource named by the type | | `IStringLocalizerFactory.Create(string baseName, string location)` | return a localizer for an explicit base name; `location` is an assembly name in the built-in factory | | `IStringLocalizer.this[string name]` | look up the key in the current UI culture | | `IStringLocalizer.this[string name, params object[] arguments]` | look up, then format | | `IStringLocalizer.GetAllStrings(bool includeParentCultures)` | enumerate the resource's strings | ## The contract the built-in localizer keeps 1. **Per resource, not per culture.** ASP.NET Core 5.0 removed `IStringLocalizer.WithCulture` and `ResourceManagerWithCultureStringLocalizer` because they suggested one instance per language. A localizer is created once per resource, cached and shared by every request, so it must not capture a culture in its constructor. 2. **Culture at lookup time.** Read `CultureInfo.CurrentUICulture` inside the indexer and walk `Parent` from `fr-CH` to `fr` to the invariant culture, mirroring `.resx` fallback. 3. **Never throw, never return null.** A miss returns `new LocalizedString(name, name, resourceNotFound: true, searchedLocation: ...)`. Views, DataAnnotations and your callers rely on the key coming back. 4. **Format with `CurrentCulture`.** The built-in localizer calls `string.Format(CultureInfo.CurrentCulture, format ?? name, arguments)`. 5. **Thread safety.** The factory is a singleton and its localizers serve concurrent requests. ## Registering it `AddLocalization` registers its services with `TryAdd`: ```csharp builder.Services.AddSingleton<ITranslationSnapshot, TranslationSnapshot>(); builder.Services.AddSingleton<IStringLocalizerFactory, DbStringLocalizerFactory>(); builder.Services.AddLocalization(); // TryAdd keeps the factory above ``` Registering yours **after** `AddLocalization` also works, because a single-service resolution takes the last registration, but registering first leaves only one descriptor in the collection. ## Getting data in without hurting requests The indexers are synchronous and pages call them dozens of times. A database round trip per string is too slow, and blocking on async I/O inside an indexer risks thread-pool starvation. The usual design: - an in-memory **snapshot** keyed by (resource, culture, key), loaded at startup; - a refresh path when translators publish: a timer in a hosted service, or an admin endpoint that reloads and swaps the snapshot atomically; - `IDbContextFactory<T>` or a dedicated connection for loading, because a scoped `DbContext` cannot be injected into a singleton factory; scope validation rejects it in Development. ## Choosing a store | Store | Who edits | Change needs a deploy? | Runtime dependency | |---|---|---|---| | `.resx` (default) | developers, via source control | yes | none | | database table | translators, via an admin screen | no, after a refresh | the database at startup and refresh | | JSON files on disk | developers or translators | usually yes | file system | A database store earns its cost when translators must publish without a release, for example product descriptions in the wine catalogue. For interface text that changes with the code, `.resx` reviewed in pull requests is simpler. ## Testing and operations - assert `ResourceNotFound` in tests to catch missing keys per culture; - record misses (`ResourceNotFound`) somewhere translators can see them; - implement `GetAllStrings` rather than throwing: it is how callers enumerate a resource, for example to hand a set of strings to client-side script. ## Mistakes interviewers listen for - a localizer that captures the culture in its constructor and serves the first request's language to everyone; - returning `null` or throwing for a missing key; - a scoped `DbContext` in the singleton factory; - a query per string.
- Why not constructor-inject the shop's DbContext into the custom factory?The factory is a singleton, and `AddDbContext` registers the context as scoped, so the injection is a captive dependency that scope validation rejects in Development. Even if it ran, one `DbContext` would be shared across concurrent requests, which it does not support. Load translations through `IDbContextFactory<T>` into a snapshot and refresh that snapshot instead.
- A background job must send an order email in the customer's language. How do you get German strings without WithCulture?Set `CultureInfo.CurrentUICulture` (and `CurrentCulture` for formatting) to the customer's culture for the duration of the work, look the strings up with the normal localizer, then restore the previous values. The localizer reads the culture at lookup time, so no per-culture instance is needed.
- A custom localizer should be created per culture, the way WithCulture used to work.
- Return null from the indexer for a missing key so callers can detect it.
- Replacing IStringLocalizerFactory leaves IViewLocalizer still reading .resx files.
- A scoped DbContext in the localizer factory is fine because localizers are per request.
- IStringLocalizer has async lookup members, so a query per string is fine.
Assumes ASP.NET Core 10; IStringLocalizer.WithCulture was removed in ASP.NET Core 5.0, so a localizer is per resource and reads CurrentUICulture on each lookup.