3

我有一个具有多个输出项目(网站、管理工具和 SOAP API 层)的解决方案。

它们各自共享解决方案中的共同项目(服务层、数据层等)。在这些常见项目之一中,我希望存储一个配置层。

现在,我们为每个输出项目提供了三个单独的 appsettings 配置文件 -

  • development.AppSettings.config
  • testing.AppSettings.config
  • production.AppSettings.config

所以总共有九个配置文件。每个项目中只使用一个,因为它们是通过使用 web.config appsettings 节点中的configSource属性来引用的。

无论如何,任何时候我们想从配置文件中添加/删除值都会变得很痛苦,因为这意味着我们必须更改所有九个文件才能做到这一点。这就是我想做的事情:

在 common 项目中,我们有如上的三个配置文件。这些将被设置为复制到输出目录,以便每个项目都有它们的副本。这些将是“基本”配置。

然后在每个项目中,我想再次拥​​有三个文件,但它们不一定必须包含与基本配置相同的值。但是,如果他们这样做了,那么基本配置值将被输出项目配置中的值覆盖。我想是配置继承的一种形式。

在应用程序启动时,我希望能够获得这两个配置文件 - 基本配置和项目配置文件。然后相应地设置应用程序设置。

我想知道的是,确定使用哪个文件的好方法是什么?另外,我想知道这是否是在大型解决方案中共享应用程序价值的好方法,是否还有另一种可能更有效的方法?

如果我处于开发模式,那么我不需要 production.appsettings.config,反之亦然,如果我处于生产模式。

在我开始获取配置之前,有没有一种简单的方法来获取我所处的模式(开发/测试/生产)?

4

3 回答 3

1

您可以拥有一组文件(3 个配置)并在您需要的任何项目中链接/共享它们。

http://www.devx.com/vb2themax/Tip/18855

希望这可以帮助。

于 2010-02-16T21:56:25.973 回答
1

经过深思熟虑,并在 03:30 上厕所后,我发现了一个可行的解决方案。

假设我们的基本配置文件中有一些 appSettings:

<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="MyValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />

在我的输出项目中,我有三个 appSettings:

<!-- This is used to identify which config to use. -->
<add key="Config" value="Development" />

<!-- Different value to the one in the base -->
<add key="MyKey2" value="NewValue2" />

<!-- This key does not exist in the base config -->
<add key="MyKey6" value="MyValue6" />

在我的 Application_Start 中,我调用了GetConfigs()

ConfigHelper.GetConfig(HostingEnvironment.MapPath("~/bin/BaseConfig"));

而实际的 GetConfigs 函数:

public static void GetConfigs()
{
  if (configMode == null)
  {
    configMode = ConfigurationManager.AppSettings.Get("Config").ToLowerInvariant();
  }

  //Now load the app settings file and retrieve all the config values.
  var config = XElement.Load(@"{0}\AppSettings.{1}.config".FormatWith(directory, configMode))
    .Elements("add")
    .Select(x => new { Key = x.Attribute("key").Value, Value = x.Attribute("value").Value })
    //If the current application instance does not contain this key in the config, then add it.
    //This way, we create a form of configuration inheritance.
    .Where(x => ConfigurationManager.AppSettings.Get(x.Key) == null);

  foreach (var configSetting in config)
  {
      ConfigurationManager.AppSettings.Set(configSetting.Key, configSetting.Value);
  }
}

现在,我的输出项目实际上具有以下配置设置:

<add key="Config" value="Development" />
<add key="MyKey1" value="MyValue1" />
<add key="MyKey2" value="NewValue2" />
<!-- And so on... -->
<add key="MyKey5" value="MyValue5" />
<add key="MyKey6" value="MyValue6" />

简单!

于 2010-03-08T18:42:04.567 回答
1

您可以使用ConfigurationManager.OpenExeConfiguration静态方法。这将允许您使用任意数量的配置文件。

您也可以尝试创建一个自定义类来存储您的所有设置。然后,您可以序列化您的对象以将其保存为文件。您可以扩展您的基本自定义配置类以适应所有其他项目。

于 2010-02-17T03:03:59.630 回答