Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IStringLocalizer in console application

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.

like image 417
Babak Avatar asked Nov 07 '22 03:11

Babak


1 Answers

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.

like image 87
bluedot Avatar answered Dec 11 '22 05:12

bluedot