Annotations localization E.g. for locode Input(Label="German text here")

Hello!

How can I localize strings in ServiceStack annotations? E.g. from a resource file. At the moment I help myself with string constants. But of course it is not possible to change the language at runtime or on startup. Surely there is a more elegant solution!

    [Input(Label = label.FirstName, Help = help.FirstName)]
    public string FirstName { get; set; }

Kind regards
Carsten Vogelsang
Germany

There’s no explicit support for localization, but all attributes are used to populate the App Metadata which you can modify at runtime with something like:

appHost.AddToAppMetadata(meta => {
    meta.EachType(type =>
    {
        type.EachProperty(p => p.Input != null, p => {
            p.Input.Label = appHost.ResolveLocalizedString(p.Input.Label);
            p.Input.Help = appHost.ResolveLocalizedString(p.Input.Help);
        });
    });
});

Where ResolveLocalizedString is an API you can override in your AppHost to return alternative text which ServiceStack uses for internal error messages.

I’ll look at doing this by default for these properties now so you’ll only need to override AppHost.ResolveLocalizedString() in future.

FYI in the latest v6.1.1 that’s now available on MyGet, the localizable strings are now being passed to ResolveLocalizedString so you can just override it in your AppHost to return the localized alternative text.

public override string ResolveLocalizedString(string text, IRequest request = null) => ...
1 Like

Thank you for your quick response and help.

1 Like

Hello Demis!

As far as I understand it correctly, when using ServiceStack 6.1.1, I only need to override the ResolveLocalizedString method in the AppHost class:

public override string ResolveLocalizedString(string text, IRequest request = null)
{ 
    //just for a test:
    string newText = text + "_addedsomething";
    System.Diagnostics.Debug.WriteLine(newText);
    return newText;
}

According to this, e.g. label

    [Input(Label = "English_FirstName")]
    public string FirstName { get; set; }

would become => “English_FirstName_addedsomething”.

I does not happen. I guess I am missing something.

Greetings

Carsten
Germany

If your ResolveLocalizedString() is never being called when you call /metadata/app.json then you’ll need to clear your NuGet packages cache to download the latest v6.1.1:

$ nuget locals all -clear

Hello Demis!

That did the trick. Thank you very much!

Greetings

Carsten
Germany

1 Like