Using Tlumach via Dependency Injection
Dependency Injection lets you instantiate libraries at one location of your code and then use them in a more generic way than with direct references to classes and objects.
Tlumach supports this model since version 1.2. At the same time, the way Microsoft implemented the interface (IStringLocalizer) - by using a string for a key/name of the translation unit - makes it error-prone. The approach Tlumach offers via auto-generated TranslationUnit instances is more robust because with it, any typo in the key/ name will be detected by the compiler. Due to this, we recommend using DI only when you are already using it in your project and need to replace your current translation code with Tlumach.
An alternative approach is to use Generator to generate TranslationUnit instances and/or string constants and then use those instances and constants as keys. As you will see below, Tlumach supports this model that provides grounds for syntax checking and avoiding typos.
What to Reference
The integration with Microsoft.Extensions.Localization is in the AlliedBits.Tlumach.Extensions.Localization package, which brings the core AlliedBits.Tlumach package with it. If you use the source code, reference the Tlumach.Extensions.Localization project. See Getting Started for use via Dependency Injection for the installation steps.
Setting Up DI
Here's the sample C# Code:
TranslationManager manager = new TranslationManager(new TranslationConfiguration(Assembly.GetExecutingAssembly(), "sample.cfg", null, TextFormat.Arb));
...
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
services.AddTlumachLocalization(
// These are the default settings. They are used when you request IStringLocalizer without context.
options =>
{
options.TranslationManager = manager;
},
// These are the options for the countext-bound IStringLocalizer<Tlumach.Sample.Strings> (the class name is an example)
provider => provider.AddContext("Tlumach.Sample.Strings", new TlumachLocalizationOptions()
{
TranslationManager = Strings.TranslationManager,
})
)
)
.Build();
What this code does is register the necessary classes and configures the options. "Global" options are used for instances of IStringLocalizer created without a context. When we want to use context and options specific to that context, we use the "provider" parameter to create and register these individual options using the name of the context.
AddTlumachLocalization registers its services once. A repeated call, for example from a library that sets up its own context, registers nothing again: it applies its first callback to the default options of the first call and its second callback to the TlumachSettingsProvider of the first call. This is the rule of the other AddTlumach... methods. AddContext is thread-safe, so contexts can also be added while the application is running, through the TlumachSettingsProvider resolved as ITlumachSettingsProvider; the localizers created afterwards use the new options.
Using Tlumach via DI
The use of Tlumach via DI and IStringLocalizer interfaces is no different from any translation engine:
var genericLocalizer = host.Services.GetRequiredService<IStringLocalizer>();
Console.WriteLine(genericLocalizer["HelloName", "John Doe"]);
...
var localizer = host.Services.GetRequiredService<IStringLocalizer<Strings>>();
Console.WriteLine(localizer["Welcome"]);
// or use this form which enables syntax checking.
// WelcomeKey is a string constant, generated by Generator
Console.WriteLine(localizer[Strings.WelcomeKey]);
Do not pass a translation unit such as Strings.Welcome to a localizer. The unit has an implicit conversion to string, but the conversion yields the translated text and not the key, so the localizer
would look the text up as if it were a key. Pass the generated ...Key constant, or read the text from the unit directly with CurrentValue.
The first localizer accesses strings using the options provided as global in the setup code above.
The second localizer uses options provided for the given scope. The "Strings" type here is an autogenerated class that includes a property named "TranslationManager". The IStringLocalizer implementation will take the TranslationManager instance and use it to find the translated string with the "Welcome" name. The use of the autogenerated class also enables referencing translation units or string constants for the purpose of syntax checking. A localizer that takes its manager from the generated class processes placeholders in the text processing mode of the configuration of that class (.NET if the configuration sets none), as does a TlumachStringLocalizer created with the constructor that takes only a manager. A localizer created from options uses TextProcessingMode when it is set, and otherwise the mode of the manager as well.
Web-safe Formatting
To conveniently use Tlumach in provision of text for Razor and Blazor pages, you can make all localized strings related to a certain Translation Manager instance return web-safe data. For this, set the WebEncodeValues property of the translation manager in question to true. After that, when you access the strings via a localizer, these instances will return web-safe text strings. In Blazor, leave it off; see Getting Started for integration with Blazor. The HTML localizers of MVC and Razor Pages (IHtmlLocalizer, IViewLocalizer; see below) ignore the property: they encode the values of placeholders themselves and never encode the same text twice, whether the property is on or off.
More About Options
TlumachLocalizationOptions objects include different properties that let you reference an instance of TranslationManager or create a new instance. If the TranslationManager property is set, an IStringLocalizer implementation will use the value from this property and ignore the other settings. If the TranslationManager property is null and Configuration is not null, an IStringLocalizer implementation will use this configuration to create a new instance of TranslationManager. And if Configuration is null, the other properties are used to create an instance of TranslationConfiguration and then this new configuration is used to create an instance of TranslationManager. Note that in the latter scenario you don't need a configuration file, you need only the default translation file.
The default translation file and the other translation files are loaded from the embedded resources of the assembly set in Assembly. When this property is not set, they are loaded from the entry assembly of the process, i.e. the application. The same rule applies to the string localizers and to the HTML and view localizers, the model binding messages, and the display names of MVC and Razor Pages, so the same options give the same texts everywhere. If the translation files are embedded into a library rather than into the application, set Assembly to that library, for example options.Assembly = typeof(SomeTypeOfTheLibrary).Assembly.
When IStringLocalizerFactory.Create(baseName, location) (or IHtmlLocalizerFactory.Create(baseName, location) of MVC; see below) is called and the options for the context location.baseName have no TranslationManager, Configuration, or DefaultFile, the factory loads the default file named baseName from the assembly that location names, as ResourceManagerStringLocalizerFactory of .NET does: location is the simple or full name of the assembly that holds the resources, for example typeof(Program).Assembly.GetName().Name. So the file is found also when framework code calls the factory on behalf of the application, as HtmlLocalizerFactory and ViewLocalizer of MVC do with the name of the application. When location is empty or is not the name of a loadable assembly, the factory loads the file from the assembly that calls Create; no error is reported, because location may be meant only as a part of the options context. Options with a DefaultFile are not affected by location: their file is loaded from Assembly or the entry assembly, as described above.
Localizers are created anew for every resolution (IStringLocalizer<T> is transient), but the translation managers that the factory creates are reused: options with the same Configuration instance, or with the same DefaultFile, Assembly, and DefaultFileLocale (and the same TextProcessingMode), share one manager. The options are requested from ITlumachSettingsProvider for every localizer, so a custom provider can route a context to another manager at runtime. Such a provider may build a new options object on every call, but it should reuse the TranslationManager or TranslationConfiguration instance that it puts into the options: a new configuration on every call creates and loads a new translation manager on every call, and every manager stays in TranslationManagers until it is disposed.
Each instance of TlumachLocalizationOptions may include a reference to a different translation set.
Culture
Unless the application asks for a particular culture, a localizer reads CultureInfo.CurrentCulture at the moment of every call rather than at the moment it was created. A localizer that a container
creates while the application starts therefore follows the culture of each request of a web application, which is what the request localization middleware of ASP.NET Core sets.
To pin a localizer to one culture, call WithCulture(CultureInfo). It returns a new localizer and leaves the one whose method was called untouched, as does WithTextProcessingMode(TextFormat).
TlumachStringLocalizer<T>, the class that AddTlumachLocalization registers for IStringLocalizer<T>, has the same two methods and passes them on to the localizer that the registered IStringLocalizerFactory creates. They need the factory of Tlumach: if another factory is registered after AddTlumachLocalization, they throw InvalidOperationException, which names the type of the localizer that the other factory created, because IStringLocalizer itself offers no way to change the culture.
Blazor
In a Blazor Server application, the culture of the thread is the culture of the circuit, which does not change when the user switches the language in a running application. Call AddTlumachBlazor from Tlumach.Blazor in addition to AddTlumachLocalization (in any order): it registers scoped localizers that retrieve the strings in the culture of each user (TlumachCultureState), also after a live switch. See Getting Started for integration with Blazor.
AddTlumachBlazor registers IStringLocalizer and IStringLocalizer<T> as scoped services (one per user) and replaces the earlier registrations of these interfaces, including those of AddLocalization(). Inject the localizer into components or into scoped services. A singleton service should not inject IStringLocalizer<T>: scope validation rejects that in the Development environment. Where a localizer is nevertheless resolved outside a user's scope (a singleton with scope validation off, or a service resolved from the root provider), it follows the culture of the current request or circuit (CultureInfo.CurrentUICulture), as localizers did before AddTlumachBlazor; it does not see live switches, which belong to the user's scope. Call AddTlumachBlazor once per project (once in the server project and once in the client project of a Blazor Web App). When AddTlumachBlazor is not used and AddLocalization() is called before AddTlumachLocalization(), the framework's StringLocalizer<T> stays registered, and it still delegates to the Tlumach localizer factory.
Values and Missing Keys
The indexer without arguments returns the text of the translation entry as it stands, with the placeholders it contains left untouched, so that the value can be used as a format string. Use the indexer that takes arguments to have the placeholders replaced with values.
When a key is present in no translation at all, the value is the key itself and LocalizedString.ResourceNotFound is true, which is the behaviour that the consumers of IStringLocalizer rely on. The
indexer that takes arguments formats the key with them as a composite format string (string.Format in the culture of the localizer), as the localizer of ASP.NET Core does: the localization of data annotations
passes the default message of an attribute, such as "The {0} field is required.", as the key. A key that is not a valid composite format string for the arguments is returned as it stands. A
text that comes from the default translation rather than from the translation of the requested culture is a text that was found: ResourceNotFound stays false.
GetAllStrings returns every key once. When several translations of the culture chain carry one key, the value of the most specific culture wins, and the default translation is the last fallback.
Localization of Data Annotations
Because the localizer follows the contract of IStringLocalizer, the localization of data annotations that ASP.NET Core provides works on top of Tlumach with no further code:
builder.Services.AddTlumachLocalization(options => options.TranslationManager = Strings.TranslationManager);
builder.Services.AddRazorPages().AddDataAnnotationsLocalization();
The model metadata then resolves DisplayAttribute.Name through the localizer whenever ResourceType is not set, and the validation adapters resolve ErrorMessage the same way, so the text of an
annotation becomes a translation key. See Localization of Data Annotations for this and for the two other routes, which also cover validation outside ASP.NET.
HTML Localizers and View Localizers (MVC and Razor Pages)
IHtmlLocalizer, IHtmlLocalizer<T>, and IViewLocalizer of ASP.NET Core return HTML: the text of a translation is trusted markup, and the values of its placeholders are encoded. The stock implementations of these interfaces do not work with Tlumach, because they look for resource files named after the view. The Tlumach.AspNetCore.Mvc assembly provides implementations that take the texts from Tlumach, keyed by the path of the view:
builder.Services.AddTlumachLocalization(options => options.TranslationManager = Strings.TranslationManager);
builder.Services.AddRazorPages() // or AddControllersWithViews()
.AddTlumachViewLocalization()
.AddDataAnnotationsLocalization();
AddTlumachViewLocalization() replaces the registrations of AddViewLocalization() regardless of the order of the calls, and AddTlumachLocalization remains required, because it provides the translation managers. A view then uses @inject IViewLocalizer L and @L["Title"], which finds the key Views.Home.Index.Title for the view /Views/Home/Index.cshtml and, if there is none, the shared key Title. See Localization of MVC and Razor Pages for the keys, the encoding rules, the tag helpers, the culture selector, and the localization of model binding messages and display names, and the getting-started articles for MVC and Razor Pages.