如何使用一个基本 ConfigurationSection 类从 web.config 获取 2 个不同的部分?
我需要从 web.config 中的 viewModelSettings 部分获取数据
<vmSettings namespace="Site.Web.ViewModels" assembly="Site.Web"/>
,并能够获取像这样的命名空间 VM.Settings.Namespace VM2.Settings.Namespace
我创建了以下类,所以我可以像 VM.Settings.Namespace
一样使用它
public class VM : ConfigurationSection
{
private static VM _settings = ConfigurationManager.GetSection("vmSettings") as VM;
public static VM Settings
{
get { return _settings; }
}
[ConfigurationProperty("namespace", IsRequired = true)]
public string Namespace
{
get
{
return (string)base["namespace"];
}
}
[ConfigurationProperty("assembly", IsRequired = true)]
public string Assembly
{
get
{
return (string)base["assembly"];
}
}
}
现在,我有另一部分(vmSettings2)与上面的部分相同,但名称不同
我不想编写另一个 ConfigurationSection 类,而是使用上面的类(但它应该得到 < strong>vmSettings2 部分)并像 VM2.Settings.Namespace 一样使用它。我怎样才能实现这个?也许继承自VM类,但如何覆盖节名称?
I need to get data from viewModelSettings
section in web.config
<vmSettings namespace="Site.Web.ViewModels" assembly="Site.Web"/>
and to be able to get namespace like this VM.Settings.Namespace VM2.Settings.Namespace
I created the following class, so I could use it like VM.Settings.Namespace
public class VM : ConfigurationSection
{
private static VM _settings = ConfigurationManager.GetSection("vmSettings") as VM;
public static VM Settings
{
get { return _settings; }
}
[ConfigurationProperty("namespace", IsRequired = true)]
public string Namespace
{
get
{
return (string)base["namespace"];
}
}
[ConfigurationProperty("assembly", IsRequired = true)]
public string Assembly
{
get
{
return (string)base["assembly"];
}
}
}
Now, I have another section(vmSettings2) the same as the above one but with different name<vmSettings2 namespace="Site2.Web.ViewModels" assembly="Site2.Web"/>
I didn't want to write another ConfigurationSection class but use the above one(but it should get vmSettings2 section) and use it like VM2.Settings.Namespace. How could I implement this? Maybe inherit from VM class, but how to override the section name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能将你的VM类转换成抽象基类吗?
然后,您可以从名为 vmSettings1 和 vmSettings2 的类派生两个类,它们将仅使用基类中定义的方法?
您可以使用 VM 作为接口,但随后您将被迫为每个类实现每个方法,这可能是您希望在这里避免的事情类型。
Could you not convert your VM class into an abstract base class?
Then you could derive two classes from that called vmSettings1 and vmSettings2 which would simply use the methods defined in the base class?
You could possibly use VM as an interface but then you'd be forced to implement each method for each class which is possibly the type of thing you're hoping to avoid here.
试试这个:
Try this: