Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...