Register xml resource provider: By default XLocalizer works with .resx resource files. But to enable auto key adding we need to register XmlResourceProvider :
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.
Language navigation requruires adding a controller with the cookie code inside it, so before creating the language navigation we need to add controller support:
usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;usingBlazorLocalizationSample.Data;usingSystem.Globalization;usingXLocalizer.Translate;usingXLocalizer.Translate.MyMemoryTranslate;usingXLocalizer;usingXLocalizer.Xml;usingBlazorLocalizationSample.LocalizationResources;namespaceBlazorLocalizationSample{publicclassStartup{publicStartup(IConfigurationconfiguration){Configuration=configuration;}publicIConfigurationConfiguration{get;}// This method gets called by the runtime. Use this method to add services to the container.// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940publicvoidConfigureServices(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");});services.AddHttpClient<ITranslator,MyMemoryTranslateService>();services.AddSingleton<IXResourceProvider,XmlResourceProvider>();services.AddControllers();services.AddRazorPages().AddXLocalizer<LocSource,MyMemoryTranslateService>(ops =>{ops.ResourcesPath="LocalizationResources";ops.AutoAddKeys=true;ops.AutoTranslate=true;});services.AddServerSideBlazor();services.AddSingleton<WeatherForecastService>();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){if(env.IsDevelopment()){app.UseDeveloperExceptionPage();}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();app.UseRequestLocalization();app.UseEndpoints(endpoints =>{endpoints.MapControllers();endpoints.MapBlazorHub();endpoints.MapFallbackToPage("/_Host");});}}}