IStringLocalizer in console application
Asked Answered
T

1

6

Having a library contains resx files and using this document Globalization and localization in ASP.NET Core and adding following codes in Startup.cs we localized our web application:

services.AddMvc()
    .AddDataAnnotationsLocalization(option =>
    {
        option.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof({the-resx-library}));
    })
    .AddViewLocalization()

In controllers:

private readonly IStringLocalizer<{the-resx-library}> _localizer;
public AccountController(IStringLocalizer<{the-resx-library}> localizer)
{
    _localizer = localizer;
}

[HttpGet]
public IActionResult Index()
{
    string text = this._localizer["Hello"];
    return View();
}

The question is how can we use that resx library in a console application? That console application generates content based on user's chosen language and email it.

Tamper answered 19/8, 2018 at 14:32 Comment(0)
R
1

I used localization-culture-core, and the Microsoft.Extensions.Logging.Console package.

You can then create a resource folder and add your culture specific resource files in json. e.g.

resources

These contain resource key value pair string e.g.

{"SayHi": "Hello", "SayBye" : "Bye"}

Then use it like this :

public class Someclass
{
    private readonly IStringLocalizer _localizer;

    public Someclass()
    {

        ILogger logger = new Microsoft.Extensions.Logging.Console.ConsoleLogger("", null, false);
        _localizer = (IStringLocalizer)new JsonStringLocalizer("Resources", "TestLocalization", logger);
    }

    public void Talk()
    {
        CultureInfo.CurrentUICulture = new CultureInfo("en-US", false);
        Console.WriteLine(_localizer.GetString("SayHi"));
    }
}

I hope it can help.

Rosalinarosalind answered 13/9, 2018 at 17:34 Comment(1)
While this answer might help, it doesn't seem to really address the question of how to use .resx files in a console application.. It instead proposes switching to using .json files.Infrequency

© 2022 - 2024 — McMap. All rights reserved.