ASP.NET Core Localization with help of SharedResources

前端 未结 3 638
余生分开走
余生分开走 2020-12-07 22:48

Hi I have a question about the SharedResources file. It is glanced over in the tutorial here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization, and I\'

3条回答
  •  北海茫月
    2020-12-07 23:22

    I'd like to add the setup that's working for my team as well. It's based on the same principle as yours (of course), but I believe it allows some more flexibility on your files location, as it does not force you to put resource-related files in project root.

    My understanding is that IStringLocalizer has the concept of a placeholder Type, whose fullname will be converted into a relative path and used to find the actual resource file. To do this conversion, it also uses info from LocalizationOptions.ResourcesPath, if any.

    Say you have:

    // in ProjectRoot\Startup.cs
    
    services.AddLocalization(opts =>
    {
      opts.ResourcesPath = "Localized";
    });
    
    // in ProjectRoot\Area\Whatever\SomeClass.cs
    
    namespace Com.Company.Project.Area.Whatever
    {
      public class SomeClass
      {
        public SomeClass(IStringLocalizer localizer)
        {
          // ...
        }
      }
    }
    

    So here's what happens, step-by-step, just to give an idea:

    1. SomeClass fullname: Com.Company.Project.Area.Whatever.SomeClass
    2. convert that to .resx file path: Com\Company\Project\Area\Whatever\SomeClass.resx
    3. prefix that with ResourcesPath content: Localized\Com\Company\Project\Area\Whatever\SomeClass.resx

    That's the actual path where resource file(s) will be looked up.

    So, all in all, you can place your SharedResources.cs empty class wherever you want, as long as you replicate its fullname as a path under ResourcesPath folder under project root.

    In the example:

    \
    --Area
      --Whatever
        --SomeClass.cs
    --Localized
      --Com
        --Company
          --Project
            --Area
              --Whatever
                --SomeClass.resx
                --SomeClass.fr.resx
                --SomeClass.da.resx
    

    Under the cover, that directory tree is needed because classes generated out of resx file will take their namespace from the directory tree, and also because string localizer will not strip root namespace when prefixing placeholder type with ResourcesPath.

提交回复
热议问题