【发布时间】:2013-08-21 22:40:04
【问题描述】:
我的 apiController 中有以下方法:
public IEnumerable<something> GetData(DataProvider dataProvider)
{
return dataProvider.GetData();
}
我需要的是从 javascript 中调用此方法并将其传递给 DataProvider 派生类型的参数。我可以通过传递字符串来处理这个问题,例如“FirstProvider”,然后在 GetData() 方法中写入 N 个 if 来创建正确类型的实例。
但是有什么方法可以让我在 web.config 文件中写入类似的内容:
<DataProviders>
<type = FirstDataProvider, alias = "FirstProvider">
<type = SecondDataProvider, alias = "SecondProvider">
</DataProviders>
将getData方法改为:
public IEnumerable<something> GetData(string dataProviderAlias)
{
// get provider type by it's alias from web congfig,
// then instantiated and call:
return dataProvider.GetData();
}
然后通过别名查找并实例化类型?
注意:我接受了下面的答案,因为它为我指明了正确的方向,但 msdn 说 IConfigurationSectionHandler 已弃用。
所以我改用ConfigurationSection、ConfigurationElementCollection、ConfigurationElement 类来构建自定义配置部分。
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-mvc-4 web-config