Custom ResourceProviderFactory Dependency Injectio

2019-01-19 02:42发布

问题:

Is there anywhere in ASP.NET MVC where you can get a reference to the ResourceProviderFactory that is instantiated in order to perform Property Injection to add a custom DB Implementation to retrieve the resources from?

I have a custom resource provider being loaded but I wanted to know whether there was an alternative to using a Static DI container to inject the dependency within the Provider.

Similar to how you can inject for the Role and Membership providers in MVC.

回答1:

The trick is to implement an infrastructure component calls into MVC's DependencyResolver.Current, so you can register the real ResourceProviderFactory using your favorite DI container.

Here is such a class that will do the trick:

public class MvcResourceProviderFactory : ResourceProviderFactory
{
    public override IResourceProvider CreateGlobalResourceProvider(
        string classKey)
    {
        return GetFactory().CreateGlobalResourceProvider(classKey);
    }

    public override IResourceProvider CreateLocalResourceProvider(
        string virtualPath)
    {
        return GetFactory().CreateLocalResourceProvider(virtualPath);
    }

    private static ResourceProviderFactory GetFactory()
    {
        var resolver = DependencyResolver.Current;

        var factory = resolver.GetService<ResourceProviderFactory>();

        if (factory != null)
        {
            return factory;
        }

        throw new InvalidOperationException(string.Format(
            "No {0} has been registered in the {1}.",
            typeof(ResourceProviderFactory).FullName,
            DependencyResolver.Current.GetType().FullName));
    }
}

This class can be configured as follows:

<globalization
    resourceProviderFactoryType="MyApp.MvcResourceProviderFactory, MyApp"
    enableClientBasedCulture="true" uiCulture="auto" culture="auto"
/>