In ASP.NET Core 10, how do AddLocalization and IStringLocalizer<T> return a French or German string, and what comes back when no translation exists?
answer
- the type parameter picks the resource
- CurrentUICulture chooses the language
- indexer returns LocalizedString, not string
- ResourceNotFound and SearchedLocation
- factory singleton, IStringLocalizer<T> transient
basics
~10 sAddLocalization registers IStringLocalizer<T>, which reads the .resx resources named after T for CultureInfo.CurrentUICulture. Its indexer returns a LocalizedString; when no resource holds the key, Value is the key itself and ResourceNotFound is true.
solid answer
~40 s`builder.Services.AddLocalization(o => o.ResourcesPath = "Resources")` registers a singleton `IStringLocalizerFactory` (`ResourceManagerStringLocalizerFactory`) and a transient open generic `IStringLocalizer<T>`. Injecting `IStringLocalizer<CatalogController>` asks the factory for a localizer whose resource base name is derived from that type's full name, so it reads `CatalogController.fr.resx` or `CatalogController.de.resx`. The indexer `localizer["Out of stock"]` looks the key up for `CultureInfo.CurrentUICulture`, which request localization sets per request, and returns a `LocalizedString`. When nothing matches it does not throw: `Value` is the key itself, `ResourceNotFound` is `true` and `SearchedLocation` names the base name it searched. That is why English sentences can serve as keys and as the default text. The overload `localizer["{0} bottles left", n]` formats the arguments with `CurrentCulture`.
code
csharp · 16 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddLocalization(o => o.ResourcesPath = "Resources");
var app = builder.Build();
app.UseRequestLocalization("en", "fr", "de");
// Resources/StockText.fr.resx and Resources/StockText.de.resx hold the translations
app.MapGet("/wines/{id:int}/stock", (int id, IStringLocalizer<StockText> text) =>
{
LocalizedString badge = text["Only {0} bottles left", 3];
return Results.Ok(new { badge.Value, badge.ResourceNotFound });
});
app.Run();
public sealed class StockText { } // marker type that names the resourcego deeper
Recall the AddLocalization call, inject IStringLocalizer<T>, and say what the indexer returns when a translation is missing: the key itself with ResourceNotFound set.
Explain that the factory is a singleton that caches one localizer per type, that CurrentUICulture is read on every lookup, and that arguments are formatted with CurrentCulture.
Show how you would catch silent fallbacks: tests asserting ResourceNotFound, Debug logs from Microsoft.Extensions.Localization, and a decision on whether keys are English text or short identifiers.
Weigh keys-as-text against identifier keys for a multi-language product: translator workflow, renaming risk and how a neutral resource changes what users see when a translation lags.
## What AddLocalization registers ASP.NET Core's string localization lives in `Microsoft.Extensions.Localization`. One call wires it up: ```csharp builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); ``` | Service | Implementation | Lifetime | |---|---|---| | `IStringLocalizerFactory` | `ResourceManagerStringLocalizerFactory` | singleton | | `IStringLocalizer<T>` | `StringLocalizer<T>` | transient | Both are added with `TryAdd`, so a factory you registered first is kept. Note what is **not** registered: there is no registration for the non-generic `IStringLocalizer`, and nothing for views. `IViewLocalizer` and `IHtmlLocalizer<T>` arrive only with MVC's `AddViewLocalization()`. `StringLocalizer<T>` is a thin wrapper. Its constructor calls `factory.Create(typeof(T))`, and the factory caches one `ResourceManagerStringLocalizer` per type, so the transient wrapper is cheap. ## Asking for a string The interface has three members: - `this[string name]` returns a `LocalizedString`; - `this[string name, params object[] arguments]` returns a `LocalizedString` whose value has been run through `string.Format`; - `GetAllStrings(bool includeParentCultures)` enumerates every string the resource holds. `LocalizedString` carries `Name` (the key), `Value` (the text), `ResourceNotFound` and `SearchedLocation`. It converts implicitly to `string` and its `ToString()` returns `Value`, which is why `@localizer["Sold out"]` or string interpolation just works. The `GetString(name)` extension method is the same lookup spelled as a method. `GetAllStrings(includeParentCultures: true)` walks the culture chain and returns every string the resource holds. It is useful for handing a page's strings to client-side script, or for a test that compares the French and German resources key by key. ## Which language comes back The `IStringLocalizer` interface takes no culture argument. Each lookup reads `CultureInfo.CurrentUICulture` at the moment of the call. In a web app the request localization middleware sets that property for the request; choosing it is a separate concern. Two cultures are involved: - **`CurrentUICulture`** selects the translation, `fr` or `de`; - **`CurrentCulture`** formats the arguments: the parameterized indexer calls `string.Format(CultureInfo.CurrentCulture, format, arguments)`, so a price argument is formatted by the formatting culture, not by the translation's. The lookup itself is delegated to .NET's `ResourceManager`, which tries the specific culture, then its parent, then the neutral resource. A request in `fr-CH` therefore finds strings in `CatalogController.fr.resx` when no `fr-CH` file exists. ## When the key is missing This is the behaviour interviewers probe. `ResourceManagerStringLocalizer` asks the `ResourceManager` for the key. If the manager returns nothing, or throws `MissingManifestResourceException` because no resource exists for that base name at all, the localizer catches it and builds: ```csharp new LocalizedString(name, name, resourceNotFound: true, searchedLocation: baseName) ``` So a missing translation renders the key, never an exception and never `null`. The consequences: 1. **Keys can be the default-language text.** With keys such as `"Out of stock"` you need no English `.resx`; English requests simply get the key back. 2. **A neutral `.resx` changes the fallback.** A `CatalogController.resx` without a culture suffix is the last fallback for every culture. A key present there returns its value instead of the key. 3. **Missing translations are silent.** Nothing in the page shows that German fell back to English. Check `ResourceNotFound` in tests, or enable `Debug` logging for `Microsoft.Extensions.Localization`: every lookup logs "searched for '{Key}' in '{LocationSearched}' with culture '{Culture}'". ## Choosing a key style The API supports two conventions, and teams should pick one deliberately: | Style | Example key | Default-language text comes from | Main risk | |---|---|---|---| | Text as key | `"Only {0} bottles left"` | the key itself | editing the English sentence orphans its translations | | Identifier key | `"Stock.Low"` | a neutral `.resx` | a missing neutral entry shows `Stock.Low` to users | Text keys suit a small team that writes English first; identifier keys suit a translation workflow where English is just another resource file. ## Where you can use it Any DI-created class can take `IStringLocalizer<T>`: an MVC controller, a Razor Page model, a service, a Minimal API handler parameter or a Blazor component's `@inject`. `T` is only a name for the resource; the type can be the consumer itself or an empty marker class such as `SharedResource` that several consumers share. ## Mistakes interviewers listen for - injecting the non-generic `IStringLocalizer` and getting "Unable to resolve service"; - expecting an exception or `null` for a missing key, then writing null checks that never fire; - believing `CurrentCulture` picks the translation; - injecting one localizer per language instead of letting the request's UI culture decide; - calling `AddLocalization` and expecting `IViewLocalizer` to be injectable.
- Why does a service that takes the non-generic IStringLocalizer fail to start, and what are the two fixes?`AddLocalization` registers only `IStringLocalizer<T>` and `IStringLocalizerFactory`, so the container has no entry for plain `IStringLocalizer` and throws "Unable to resolve service". Inject `IStringLocalizer<SomeType>`, or inject `IStringLocalizerFactory` and call `factory.Create(typeof(SomeType))` when the resource is chosen at run time.
- Do you need an English .resx when the keys are already English sentences?No. A missing key returns the key, so English requests get the key text. A neutral `.resx` without a culture suffix becomes the fallback for every culture, and its values replace the key. Teams that use short keys such as `Stock.Low` need that neutral file, because otherwise the raw key would reach the page.
A waiter with a phrasebook: you say the dish's English name, and he reads the matching line from the French or German page for today's guest. If the page has no line for it, he simply says the English name aloud rather than staying silent.
- A missing key makes the indexer throw MissingManifestResourceException.
- The localizer returns a plain string, so a fallback cannot be detected.
- CurrentCulture decides which translation IStringLocalizer<T> returns.
- AddLocalization also makes IViewLocalizer injectable into Razor views.
- You inject one localizer per language, for example a French and a German one.