设置.NET 6控制台应用程序的静态文化。

huangapple go评论73阅读模式
英文:

Setting static culture for .NET 6 console application

问题

我正在尝试在.NET 6控制台应用程序中使用依赖注入静态设置文化。

我尝试设置ThreadCurrentCulture,但在我的注入服务中稍后获取当前文化时,它又恢复到原始状态。

var cultureInfo = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
CultureInfo.CurrentCulture = cultureInfo;

我还尝试了AddLocalization并在RequestLocalizationMiddleware中设置了DefaultCulture。

services.AddLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
    options.SetDefaultCulture("en-GB");
    options.AddSupportedUICultures("en-GB");
    options.FallBackToParentUICultures = true;
});

我的startup.cs文件如下:

try
{
    var host = CreateHostBuilder(args).UseSerilog().Build();

    await host.Services.GetService<TestGenerator>().ExecuteAsync(args);
}
catch (Exception ex)
{
    Log.Fatal(ex, "An unhandled exception occurred during startup");
    Log.CloseAndFlush();
    Environment.Exit(-1);
}
finally
{
    Log.CloseAndFlush();
}

static IHostBuilder CreateHostBuilder(string[] args)
{
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =>
        {
            builder.SetBasePath(Directory.GetCurrentDirectory());
        })
        .ConfigureServices((context, services) =>
        {
            ConfigureServices(services);
        });

    return hostBuilder;
}

static IServiceCollection ConfigureServices(IServiceCollection services)
{
    var cultureInfo = new CultureInfo("en-GB");
    CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
    CultureInfo.CurrentCulture = cultureInfo;

    var config = LoadConfiguration();

    // 初始化Serilog Logger
    Serilog.Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(config)
        .CreateLogger();

    // 添加对通用IConfigurationRoot的访问
    services.AddSingleton(config);

    services.AddLocalization();
    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.SetDefaultCulture("en-GB");
        options.AddSupportedUICultures("en-GB");
        options.FallBackToParentUICultures = true;
    });

    // 添加服务
    services.AddHttpClient();
    services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

    // 注册生成器
    services.AddTransient<TestGenerator>();

    return services;
}

static IConfiguration LoadConfiguration()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

    return builder.Build();
}

希望这对你有所帮助!如果你有任何其他问题,请随时提出。

英文:

I'm trying to statically set the culture of a .NET 6 console application with dependency injection.

I've tried setting the ThreadCurrentCulture but later in my injected service I get the current culture and it's back to the original.

var cultureInfo = new CultureInfo(&quot;en-GB&quot;);
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
CultureInfo.CurrentCulture = cultureInfo;`

I've also tried AddLocalization and setting the DefaultCulture from the RequestLocalizationMiddleware

services.AddLocalization();
services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt;
{
    options.SetDefaultCulture(&quot;en-GB&quot;);
    options.AddSupportedUICultures(&quot;en-GB&quot;);
    options.FallBackToParentUICultures = true;
});

My startup.cs file

try
{
    var host = CreateHostBuilder(args).UseSerilog().Build();

     await host.Services.GetService&lt;TestGenerator&gt;().ExecuteAsync(args);
}
catch (Exception ex)
{
    Log.Fatal(ex, &quot;An unhandled exception occurred during startup&quot;);
    Log.CloseAndFlush();
    Environment.Exit(-1);
}
finally
{
    Log.CloseAndFlush();
}

static IHostBuilder CreateHostBuilder(string[] args)
{
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =&gt;
        {
            builder.SetBasePath(Directory.GetCurrentDirectory());
        })
        .ConfigureServices((context, services) =&gt;
        {
            ConfigureServices(services);
        });

    return hostBuilder;
}

static IServiceCollection ConfigureServices(IServiceCollection services)
{
    var cultureInfo = new CultureInfo(&quot;en-GB&quot;);
    CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
    CultureInfo.CurrentCulture = cultureInfo;

    var config = LoadConfiguration();

    // Initialize Serilog Logger

    Serilog.Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(config)
        .CreateLogger();

    // Add access to generic IConfigurationRoot

    services.AddSingleton(config);

    services.AddLocalization();
    services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt;
    {
        options.SetDefaultCulture(&quot;en-GB&quot;);
        options.AddSupportedUICultures(&quot;en-GB&quot;);
        options.FallBackToParentUICultures = true;
    });

    // Add services

    services.AddHttpClient();
    services.AddTransient&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
    
    // Register Generators

    services.AddTransient&lt;TestGenerator&gt;();

    return services;
}

static IConfiguration LoadConfiguration()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile(&quot;appsettings.json&quot;, optional: true, reloadOnChange: true);

    return builder.Build();
}

答案1

得分: 0

文化设置通过以下代码被正确设置:

var cultureInfo = new CultureInfo("en-GB");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
CultureInfo.CurrentCulture = cultureInfo;

但是文化信息被用户设置覆盖了,使用CultureInfo的第二个参数解决了这个问题:

var cultureInfo = new CultureInfo("en-GB", false);

参考:https://stackoverflow.com/questions/66804391/cultureinfo-changes-based-on-computer-settings

英文:

The culture was being set correctly by the following code:

var cultureInfo = new CultureInfo(&quot;en-GB&quot;);
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
CultureInfo.CurrentCulture = cultureInfo;

But the CultureInfo was being overwritten by user settings, using the second parameter of CultureInfo solved this.

var cultureInfo = new CultureInfo(&quot;en-GB&quot;, false);

See: https://stackoverflow.com/questions/66804391/cultureinfo-changes-based-on-computer-settings

huangapple
  • 本文由 发表于 2023年7月17日 21:17:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定