Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

asp.net mvc - Custom ResourceProviderFactory Dependency Injection

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...