Toars I will smile to the world ^o^

11Aug/090

How to have customized ResourceProvider and ResourceProviderFactory

It is not flexible to use the default ResourceProvider to access the resources. Different applications have different requirements, such as storing the resource files in another folder other than the default App_GlobalResources, having shorter naming conventions, or other purposes.

Thus, it would be much better and flexible to have our own customized ResourceProvider.

I create two classes in my project, ResourceProvider.cs and ResourceProviderFactory.cs, where ResourceProvider implements the interface System.Web.Compilation.IResourceProvider, and ResourceProviderFactory overrides System.Web.Compilation.ResourceProviderFactory.

In the ResourceProviderFactory.cs file:

namespace Web.Core
{
    public class ResourceProviderFactory: System.Web.Compilation.ResourceProviderFactory
    {
        public override IResourceProvider CreateGlobalResourceProvider(string classKey)
        {
            return new ResourceProvider();
        }
    }
}



In the ResourceProvider.cs file:

namespace Web.Core
{
    public class ResourceProvider: IResourceProvider
    {
        private ResourceManager resourceManager;

        public void ResourceProvider(string defaultNameSpace, string folder)
        {
            if (resourceManager == null)
                resourceManager = new ResourceManager(defaultNameSpace, Assembly.Load(folder));
        }

        public object GetObject(string resourceKey, CultureInfo culture)
        {
            string value = resourceManager.GetString(resourceKey, culture);

            if(string.IsNullOrEmpty(value))
                return "Do Something Here";
            else
                return "Do Something Else Here";
        }
    }
}



In the Web.Config file: add the section below to <system.web>

<globalization resourceProviderFactoryType="Web.Core.ResourceProviderFactory, Web.Core"
               enableClientBasedCulture="true" uiCulture="auto" culture="auto" />