I am asked to implement localization in a net.core
solution as following:
Resource files must be in a separated project (like "MyProject.Common") to be used in all other projects in the solution,
Resources must be split by "sections", for example, we have 3 areas in the Web project like following :
Users
,Content
,Administration
,
So I'm asked to have something like:
- UsersResources.fr-CA.resx,
- UsersResources.en-CA.resx,
- ContentResources.fr-Ca.resx,
- ...
I started to read documentation for Localization is AP-NET core and I'm a bit confused on how itr works. Doesn't seem like what i'm told to do is possible.
Thing is, I may need to use resources in Business, Views and Controllers so I'm searching for a way to implement it so the team could use the old way, by calling ContentResources.MyCustomResource
.
Is there a way to get close from that?
I found a post where someone was mentioning https://www.nuget.org/packages/ResXResourceReader.NetStandard.
But I don't know if it will fit my needs...
#EDIT : So, trying to implement Laz's solution for shared resources.
So far, in startup I have this :
in ConfigureServices
:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResources));
services.AddLocalization();
services.Configure<RequestLocalizationOptions>(
opts =>
{
/* your configurations*/
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("fr")
};
opts.DefaultRequestCulture = new RequestCulture("fr", "fr");
opts.SupportedCultures = supportedCultures;
opts.SupportedUICultures = supportedCultures;
}
);
and in Configure
:
app.UseRequestLocalization();
// used to force culture to fr but doen't seem to work
var cultureInfo = new CultureInfo("fr");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
in MyProject.Common, I have this structure:
MyProject.Common
-Resources
--SharedResources.cs
---SharedResources.fr.resx
---SharedResources.en.resx
--UsersResources.cs
---UsersResources.fr.resx
---UsersResources.en.resx
Let's say I want to use SharedResources
.
In SharedResources.en.resx
I added resources:
In SharedResources.fr.resx
I added resources:
Now in my UserService
, in Business
layer, I did this:
private readonly IStringLocalizer Localizer;
public UserService(IStringLocalizerFactory factory)
{
var type = typeof(SharedResources);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create(type);
}
public void Test()
{
var test = Localizer["Test"]; //using the key of resources file i want
}
but all I get as a result in test
variable is "Test", which is the key
of the resource, and not the value
.