Localization based on XML files works very similar to RESX process, we only use .xml files instead of .resx to store resources. But the ability to edit XML files at run time gives us the flexibility of automtically adding missing resources to XML resource files.
Notice: To install the latest preview add -Pre to the command line
Create resources folder
Let's start by creating a folder and a dummy class for our localized resources.
Create a new folder under the root of the project and name it LocalizationResourcesor anything else...
Create a new class inside LocalizationResources folder and name it LocSourceor anything else...
Do not create resource files manually! they will be created automatically by XLocalizer.
The folder structure will be like below:
ProjectRoot/
LocalizationResources/
LocSource.cs
LocSource is empty class, it will be used only to refere to .resx resource files inside the code.
publicclassLocSource{}
Startup settings
Configure request localization options and optionally add RouteSegmentRequestCultureProvider :
// Add namespace for optional routing setupusingXLocalizer.Routing;// Configure request localization optionsservices.Configure<RequestLocalizationOptions>(ops =>{// Define supported culturesvarcultures=newCultureInfo[]{newCultureInfo("en"),newCultureInfo("tr"),newCultureInfo("ar")};ops.SupportedCultures=cultures;ops.SupportedUICultures=cultures;ops.DefaultRequestCulture=newRequestCulture("en");// Optional: add custom provider to support localization based on {culture} route valueops.RequestCultureProviders.Insert(0,newRouteSegmentRequestCultureProvider(cultures));});
Register xml resource provider: By default XLocalizer works with .resx resource files. But to enable auto key adding we need to register XmlResourceProvider :
If TranslateFromCulture is not defined, the default request culture will be used as source culture for translation.
Configure the app to use request localization middleware:
app.UseRequestLocalization();
User secrets
MyMemory offers a free or paid subscriptions, and depending on your setup it may require an Api key to be provided, for more details see MyMemoryTranslateService.
XLocalizer has built-in caching enabled by default. Caching helps to speedup the retriving of localized resources. But, it is recommended to switch caching off during development to avoid caching values that are subject to change frequently.
ops.UseExpressMemoryCache=false;
Full startup code for XML
usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;usingXLocalizer.Translate;usingXLocalizer;usingXLocalizer.Xml;usingSystem.Globalization;usingXLocalizer.Routing;usingXLocalizer.Translate.MyMemoryTranslate;usingXmlLocalizationSample.LocalizationResources;namespaceXmlLocalizationSample{publicclassStartup{publicStartup(IConfigurationconfiguration){Configuration=configuration;}publicIConfigurationConfiguration{get;}// This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollectionservices){services.Configure<RequestLocalizationOptions>(ops =>{varcultures=newCultureInfo[]{newCultureInfo("en"),newCultureInfo("tr"),newCultureInfo("ar")};ops.SupportedCultures=cultures;ops.SupportedUICultures=cultures;ops.DefaultRequestCulture=newMicrosoft.AspNetCore.Localization.RequestCulture("en");// Optional: add custom provider to support localization based on route value {culture}ops.RequestCultureProviders.Insert(0,newRouteSegmentRequestCultureProvider(cultures));});// Optional: To enable online translation register one or more translation servicesservices.AddHttpClient<ITranslator,MyMemoryTranslateService>();// Comment below line to switch to RESX based localization.services.AddSingleton<IXResourceProvider,XmlResourceProvider>();services.AddRazorPages()// Optional: Add {culture} route template to all razor pages routes e.g. /en/Index.AddRazorPagesOptions(ops =>{ops.Conventions.Insert(0,newRouteTemplateModelConventionRazorPages());})// Add XLocalization with a default resource <LocSource>// and specify a service for handling translation requests.AddXLocalizer<LocSource,MyMemoryTranslateService>(ops =>{ops.ResourcesPath="LocalizationResources";ops.AutoAddKeys=true;ops.AutoTranslate=true;});}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){if(env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseDatabaseErrorPage();}else{app.UseExceptionHandler("/Error");// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();// Use request localization middlewareapp.UseRequestLocalization();app.UseEndpoints(endpoints =>{endpoints.MapRazorPages();});}}}