Harris
Harris

Reputation: 1138

.NET core 1.1 and localization in runtime

In an application I am developing there is a demand for output messages to be localized. I my web api project I have succeed it with the globalization/localization features of .net core. Each user has a specific locale in the database, so with a custom RequestCultureProvider I have managed to access user's principal, grab his language and alter RequestCultureProvider. But sometimes I run procedures which send push notifications messages to users. For example:

    foreach(var user in users) 
        await SendNotification("message", user.DeviceId)

If I rewrite like: await SendNotification(localizer["message"], user.DeviceId) then each user will have the same translation of "message". Is it possible to change in runtime the localizer according to user.cultureInfo?

Thanks

Upvotes: 0

Views: 131

Answers (1)

Tseng
Tseng

Reputation: 64288

Of course you can.

You just need to call the localizer with .WithCulture(...)

foreach(var user in users)
    await SendNotification(localizer.WithCulture(new Culture("en-US"))["message"], user.DeviceId)

Of course replacing the en-US with a variable or property which contains the culture, i.e.

foreach(var user in users)
    await SendNotification(localizer.WithCulture(new Culture(user.CultureInfo))["message"], user.DeviceId)

Upvotes: 1

Related Questions