Wolfgang Gertzen
Wolfgang Gertzen

Reputation: 31

Blazor localization in class library

I'm building up a server side Blazor application. Inside this Blazor app I already have the localization running using the "IStringLocalizer" mechanism.

Now my project has grown and I want to reuse components, so I created a razor class library where I put all my reusable components in.

 Solution
    |
    |-- VISU   (the Blazor Project project)
    |
    |-- UI.Components  (RCL project containing the components)

The components contain some text which must be translated dependent on the actual culture.

At the RCL I did following.

a) I create a folder "Resources"

   UI.Components (RCL Project)
      |
      |- Resources

b) inside the "Resource Folder" I create the resource "UIComponentText.resx" file containing the translation

c) inside the "Resource" folder I create a file containing the dummy class "UIComponentText" Furthermore I create a service class "UIComponentLocalizer"

 public class UIComponentText
    {
    }
    public class UIComponentLocalizer
    {
        private readonly IStringLocalizer _localizer;

        public UIComponentLocalizer(IStringLocalizerFactory factory)
        {
            var type         = typeof(UIComponentText);
            var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
            _localizer = factory.Create("UIComponentText", assemblyName.Name);
            var    all = _localizer.GetAllStrings(false);  // test to see content
        }

        public LocalizedString this[string key] => _localizer[key];

        public LocalizedString GetLocalizedString(string key)
        {
            return _localizer[key];
        }
    }

d) Inside startup.cs of the Blazor app, I register the service

 services.AddSingleton<UIComponentLocalizer>();

e) Inside a component I inject the service to make use of it

     [Inject] public UIComponentLocalizer CompTranslate { get; set; }

--> Finally it does not work. :-(

The UIComponentLocalizer service is started, but the dictionary is empty.

Actually, I'm thinking that the access to the resource file is wrong. The component resource has the namespace "UI.Components.Resources.UIComponentText" which is not like the resources inside the Blazor project ("VISU.Resources.xyz")

Questions: a) is it possible to create a RCL which includes localization which can be "includes" inside a Blazor serve side app.

b) If yes? Where do I make a mistake

Thanks Wolfgang

Upvotes: 3

Views: 1519

Answers (1)

David
David

Reputation: 150

Try to add your Resource file via the builder.Services:

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

And go from there. Maybe this helps too: Blazor Localization

Upvotes: 0

Related Questions