C# – Localization. Extending ASP.NET Resx Resource Provider

asp.netcglobalizationlocalization

For my website I have a custom resource provider for localization purposes (localized strings are stored in database). It works just fine, but I would like it to work with the default Resx Resource Provider: look up localized string in resx resources and if doesn't exist then pull it from the database.

But it looks that as soon as I change IIS globalization setting to use my own resource provider factory, then the default resx resource provider factory gets ignored.

I guess the solution would be to extend my own resource provider, but I can't find how to reference resx resources from inside of my resource provider.

Thanks.

Best Answer

Edit

My answer below is wrong, as pointed out in the comments. You can get the ResXResourceProviderFactory by using reflection as follows.

IResourceProvider resxProvider;
string typeName = "System.Web.Compilation.ResXResourceProviderFactory, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
ResourceProviderFactory factory = (ResourceProviderFactory)Activator.CreateInstance(Type.GetType(typeName));
resxProvider = factory.CreateGlobalResourceProvider(classKey);

(Similar method to get the Local resources provider.)

Then, to get a resource, all that's needed is to call GetObject:

object resource = p.GetObject("ResourceKey", new System.Globalization.CultureInfo("en"));

You can use the GetGlobalResourceObject and GetLocalResourceObject methods (part of the HttpContext class) to work with .ResX files within your custom localization classes.

For example, to get a resource called "ResourceKey" from "MyResxFile.resx" (under *App_GlobalResources*), for the current culture, you would use this:

HttpContext.GetGlobalResourceObject(
    "MyResxFile", 
    "ResourceKey", 
    System.Threading.Thread.CurrentThread.CurrentCulture
);
Related Topic