自定义ResourceProviderFactory依赖注入

时间:2012-05-16 13:48:20

标签: asp.net-mvc dependency-injection resourceproviderfactory

ASP.NET MVC中是否有任何地方可以获取对实例化的ResourceProviderFactory的引用,以便执行Property Injection以添加自定义数据库实现以从中检索资源?

我有一个自定义资源提供程序正在加载但我想知道是否有替代方法使用静态DI容器在Provider中注入依赖项。

类似于如何为MVC中的角色和成员资格提供者注入。

1 个答案:

答案 0 :(得分:4)

诀窍是将基础架构组件调用实现到MVC的DependencyResolver.Current,这样您就可以使用自己喜欢的DI容器注册真实的ResourceProviderFactory

这是一个可以解决问题的类:

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));
    }
}

此类可以配置如下:

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