Search code examples
c#web-services.net-corelocalizationresx

GetString always return default language resource


I have a microservice in .Net-Core that have to handle some resources in a resx file and return them based on the culture I provide with a call to an API so I will not use the culture of the current thread, but when I call the method GetString(key, culture) it always return the default language. I have 2 resx file at the moment: resource.resx and resource.it-IT.resx if i call the api with the it-IT culture string I always get the translation in the resource.resx file and not in the resource.it-IT.resx file

The resx files are in another project called Localization

I have a generic method where I pass the Enum I have to localize and the type of the file where the localization is stored, then I compose the key of the resource and call the GetString method. I have also tried changing the culture of the current thread with

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName);
public static string GetDisplayName(this Enum e, Type resourceType, string cultureName)
{
   var rm = new ResourceManager(resourceType);

   var resourceDisplayName = rm.GetString(e.GetType().Name + "_" + e, CultureInfo.CreateSpecificCulture(cultureName));

   return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;
 }

I have investigated a bit more and in the resource manager when I inspect it I have 3 resourceSet

resource
resource.it
resource.it-IT

If I inspect inside these 3 resource set I have all my resource always in English it seems that the resource manager doesn't load the resx italian file


Solution

  • After reading this: NetCore Bug I managed to solve my problem, first of all I have refactored my method to this:

     public static string GetDisplayName(this Enum e, Type resourceType, string cultureName)
        {
            var rm = new ResourceManager(resourceType.FullName, resourceType.Assembly);
    
            var key = $"{e.GetType().Name}_{e}";
            var culture = CultureInfo.CreateSpecificCulture(cultureName);
            var resourceDisplayName = rm.GetString(key, culture);
    
            return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;
        }
    

    Then I have removed the reference to the Localization project from the API project and only left that reference in another project that is then referenced from the API project