Localization using multiple resx files

My web application handles localization through a resource file hosted in the satellite assembly using the ResourceManager. As the application grows, I would like to split the resx file into several files (for each language), but on the client side it seems that I need to create an instance of ResourceManager for each file I want to read. Is there a way to wrap multiple resx files in one file?

thank

+3
source share
1 answer

If you use websites (ASP.NET Website Project Template), you can do this: HttpContext.GetGlobalResourceObject(classKey, resourceKey)where classKey is the name of your .resx file and resourceKey is the localized string of your resource.

If you use WebApplications and you have resources as a separate project (C # library), you can take a look at this code:

public class SatelliteResourceManager
    {
        private const string Resources = "Resources";
        private readonly string _assemblyName;

        public SatelliteResourceManager(string assemblyName)
        {
            _assemblyName = assemblyName;
        }

        public Assembly Assembly { get { return Assembly.Load(_assemblyName); } }

        protected IEnumerable<Type> ResourceTypes
        {
            get
            { 
                return Assembly.GetTypes().Where(a => a.IsClass && a.Namespace == Resources);
            }
        }

        public IEnumerable<ResourceManager> GetAllManagers()
        {
            foreach (var manager in ResourceTypes)
            {
                yield return (ResourceManager) manager.GetProperty("ResourceManager").GetValue(this, null);
            }
        }

        public string GetGlobalResource(string classKey, string resourceKey, string fallback)
        {
            var manager = GetAllManagers().FirstOrDefault(m => m.BaseName.EndsWith(classKey, StringComparison.InvariantCultureIgnoreCase));
            if (manager != null) return manager.GetString(resourceKey);
            return fallback;
        }
    }

You need to specify the class by passing a parameter with the name of the assembly of the resource project, you can get this information from the project properties. I also added the “Resources” field, this should be useful if you decide to override the default namespace for each .resx file, keep in mind that you can extend this class to allow multiple “namespaces” for your .resx files (screenshot attached)

Using Custom Namespaces

0
source

Source: https://habr.com/ru/post/1760551/


All Articles