控制台应用程序中的 IStringLocalizer

Bab*_*bak 5 localization console-application .net-core

拥有一个包含resx文件的库,并在 ASP.NET Core 中使用本文档全球化和本地化,并在 Startup.cs 中添加以下代码,我们本地化了我们的 Web 应用程序:

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

在控制器中:

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();
}
Run Code Online (Sandbox Code Playgroud)

问题是我们如何在控制台应用程序中使用resx库?该控制台应用程序根据用户选择的语言生成内容并通过电子邮件发送。

blu*_*dot 1

我使用了localization-culture-core和 Microsoft.Extensions.Logging.Console 包。

然后,您可以创建一个资源文件夹并以 json 格式添加特定于文化的资源文件。例如

资源

这些包含资源键值对字符串,例如

{"SayHi": "Hello", "SayBye" : "Bye"}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它能有所帮助。