在ASP.NET Core和.NET Core控制台项目中使用相同的`.resx`文件

5

我已按照以下方式在ASP.NET Core中实现了本地化:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization

我有一个通用库项目(MyProject.Common),在其中保留资源文件(因为它会被多个ASP.NET Core应用程序使用)。

因此,在MyProject.Common\Resources\Localization\SharedResources.sv.resx下,我有一个.resx文件:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="English string" xml:space="preserve">
    <value>Swedish string</value>
  </data>
</root>

我有一个空的.cs文件位于MyProject.Common\Localization\SharedResources.cs下面,内容如下:

namespace MyProject.Common.Localization
{
    /// <summary>
    /// This is just a placeholder so that we can have all our resources in the same .resx file
    /// </summary>
    public class SharedResources
    {
    }
}

我有一个叫做Localizer的类,用于获取翻译后的字符串:

using System;
using Microsoft.Extensions.Localization;

namespace MyProject.Common.Localization
{
    public class Localizer
    {
        private readonly IStringLocalizer _localizer;

        public Localizer(IStringLocalizer<SharedResources> localizer)
        {
            _localizer = localizer;
        }

        public virtual LocalizedString this[string name]
        {
            get
            {
                if (name == null)
                {
                    throw new ArgumentNullException(nameof(name));
                }

                return _localizer[name];
            }
        }

        public virtual LocalizedString this[string name, params object[] arguments]
        {
            get
            {
                if (name == null)
                {
                    throw new ArgumentNullException(nameof(name));
                }

                return _localizer[name, arguments];
            }
        }
    }
}

它的使用方式如下(如果请求的文化是瑞典文化,将返回瑞典语翻译):

_localizer["English string"];

在每个ASP.NET Core项目的Startup.cs中,我像这样配置本地化:
services
    // Add the localization services to the services container
    .AddLocalization(options => options.ResourcesPath = "Resources")

    // Configure supported cultures and localization options
    .Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new[]
        {
            new CultureInfo("en"),
            new CultureInfo("sv")
        };

        // State what the default culture for your application is. This will be used if no specific culture
        // can be determined for a given request.
        options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en");

        // You must explicitly state which cultures your application supports.
        // These are the cultures the app supports for formatting numbers, dates, etc.
        options.SupportedCultures = supportedCultures;

        // These are the cultures the app supports for UI strings, i.e. we have localized resources for.
        options.SupportedUICultures = supportedCultures;
    });

我正在尝试弄清楚如何在(.NET Core)控制台应用程序中重复使用此内容?如果我尝试通过依赖注入使用我的自定义本地化(Localizer),我会得到如下错误信息:'Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.Extensions.Localization.ResourceManagerStringLocalizerFactory。这是因为Microsoft.Extensions.Localization依赖于ASP.NET Core,在我的控制台项目中不存在。

我该如何在我的控制台项目中使用相同的.resx文件呢?

1个回答

3

我知道我来晚了,但你应该能够直接访问你的翻译。当然,在控制台应用程序中不存在请求本地化的概念,因此您需要手动处理区域设置查找/存储/等等,但一旦您知道区域设置,就可以像这样访问您的翻译(无需依赖注入!):

var german = new System.Globalization.CultureInfo("de-DE");
var english = new System.Globalization.CultureInfo("en-AU");

// result "Guten tag"
var greeting1 = Shared.Resources.Lang.ResourceManager.GetString("GREETING", german); 

// result "Gidday mate"
var greeting2 = Shared.Resources.Lang.ResourceManager.GetString("GREETING", english);

你可能可以想出一种处理语言代码和资源令牌的好方法,但这应该足以处理你的公共资源文件翻译。

注意:这在 .Net Core 2.0 中可行,未在其他版本中进行测试。


很高兴你来晚了 ;). 我正在尝试做到这一点,但没有成功。我创建了两个ResX文件,一个是中性的,另一个是特定于文化的,但我总是得到中性值。这听起来对你来说很熟悉吗? 详情请见:https://github.com/dotnet/core/issues/1036 - Philipp Sumi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接