Why does this error occure? dotnet core mvc localization
Asked Answered
J

3

6

I'm trying to localize my .Net Core 2.2 MVC Website and I created a test project and copy and pasted these instructions: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.2

After that I tried getting the localized string and went on www.../Info/TestLoc

InfoController:

public class InfoController : Controller
{
    private readonly IStringLocalizer<InfoController> _localizer;
    private readonly IStringLocalizer<SharedResource> _sharedLocalizer;

    public InfoController(IStringLocalizer<InfoController> localizer,
                   IStringLocalizer<SharedResource> sharedLocalizer)
    {
        _localizer = localizer;
        _sharedLocalizer = sharedLocalizer;
    }

    public string TestLoc()
    {
        string msg = "Shared resx: " + _sharedLocalizer["Hello!"] +
                     " Info resx " + _localizer["Hello!"];
        return msg;
    }
}

But I'm getting this error:

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Localization.IStringLocalizer`1[Localization.Controllers.InfoController]' while attempting to activate 'Localization.Controllers.InfoController'.

Now I googled about that error and I found that this error occures when you aren't assigning a type. I'm doing that.

I really am clueless right now because I just copy and pasted the whole microsoft tutorial and it won't work.

I hope you guys understand my problem and I hope you can help me.

Thanks in advance I really appreciate you taking your time to read this and help me.

Greetings Nico aka Myridor

Johann answered 15/2, 2019 at 7:30 Comment(0)
T
-1

The error mentioned shows that injection didn't happen, i.e., the .net core was not able to inject the service as it didn't had any corresponding implementation. Which can happen if you haven't copied changes of startup.cs file. (If you were copying the files manually)

Trichromatism answered 15/2, 2019 at 11:5 Comment(0)
T
10

A wild guess, since you never posted your startup file, but did you copy+paste and forget to include this snippet?

services.AddLocalization(options => options.ResourcesPath = "your-translations-folder");
Tanka answered 27/1, 2020 at 22:12 Comment(0)
D
3

For .Net 6 in program.cs try adding the below snippet

builder.Services.AddLocalization(options => options.ResourcesPath = "Resource folder");
Dowzall answered 8/8, 2022 at 11:17 Comment(0)
T
-1

The error mentioned shows that injection didn't happen, i.e., the .net core was not able to inject the service as it didn't had any corresponding implementation. Which can happen if you haven't copied changes of startup.cs file. (If you were copying the files manually)

Trichromatism answered 15/2, 2019 at 11:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.