自定义 ResourceProviderFactory 依赖注入 [英] Custom ResourceProviderFactory Dependency Injection
问题描述
在 ASP.NET MVC 中是否有任何地方可以获得对实例化的 ResourceProviderFactory 的引用,以便执行属性注入以添加自定义数据库实现以从中检索资源?
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?
我正在加载一个自定义资源提供程序,但我想知道是否有替代使用静态 DI 容器在提供程序中注入依赖项的方法.
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.
类似于在 MVC 中为 Role 和 Membership 提供程序注入的方式.
Similar to how you can inject for the Role and Membership providers in MVC.
推荐答案
诀窍是实现一个基础设施组件调用到 MVC 的 DependencyResolver.Current
,这样你就可以注册真正的 ResourceProviderFactory
使用您最喜欢的 DI 容器.
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));
}
}
这个类可以配置如下:
<globalization
resourceProviderFactoryType="MyApp.MvcResourceProviderFactory, MyApp"
enableClientBasedCulture="true" uiCulture="auto" culture="auto"
/>
这篇关于自定义 ResourceProviderFactory 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!