how is it possible to configure the middleware to localize an "asp.net 7.0 razor pages" application (no mvc) using a single resource file?
I tried with the following configuration:
string culture = "it";
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddDbContext<OWsefaWebContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("OWsefaWebContext") ?? throw new InvalidOperationException("Connection string 'OWsefaWebContext' not found.")));
// Add services to the container.
builder.Services.AddRazorPages()
.AddDataAnnotationsLocalization(opts =>
{
opts.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName!);
return factory.Create(nameof(SharedResource), assemblyName.Name!);
};
})
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
DataInitializer.Initialize(services);
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseRequestLocalization(culture);
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting()
app.UseAuthorization();
app.MapRazorPages();
app.Run();
But it seems not to be enough.
Page localization:
@page
@using Microsoft.Extensions.Localization;
@inject IStringLocalizer localizer
@model OWsefa.Web.Pages.Companies.IndexModel
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<h1>@localizer["Text.Index"]</h1>
When I run the application I get the following error: InvalidOperationException: No service for type 'Microsoft.Extensions.Localization.IStringLocalizer' has been registered.
Who can help me?
Thank you.
ste
InvalidOperationException: No service for type 'Microsoft.Extensions.Localization.IStringLocalizer' has been registered.
To avoid this error. try to add specify supplying Resource class name like IStringLocalizer<ResourceClassName>
:
Change the :
@inject IStringLocalizer localizer
into:
@inject IStringLocalizer<SharedResource> localizer