2011-04-21 242 views
3

我有一个WCF数据服务,有一些方法在page_load事件期间异步调用。configSource绝对路径变通

我需要一个解决方案从脚本或控制台应用程序调用这些方法(如有必要)。

我创建了一个引用WCF .dll库的控制台应用程序。我必须将WCF服务下web.config中的一些配置变量复制到控制台应用程序下的app.config中。

我想让app.config自动镜像web.config,或者以某种方式将控制台应用程序指向WCF服务web.config。

我的控制台应用程序和wcf项目在相同的解决方案中彼此相邻,所以'configSource'属性不会工作。不允许父目录或绝对路径。

有没有人知道这方面的解决办法?

+0

什么配置变量,你需要复制? – BrandonZeider 2011-04-21 19:48:36

+0

我在configSections元素中定义了一个自定义配置节,以及连接字符串。就是这两个。 – 2011-04-21 19:57:40

回答

3

好的,我不知道你的自定义配置部分是什么,但是这个类将告诉你如何以编程方式检索配置节(本例中是system.serviceModel/client),应用程序设置和连接字符串。您应该可以对其进行修改以适应您的需求。

public class ConfigManager 
{ 
    private static readonly ClientSection _clientSection = null; 
    private static readonly AppSettingsSection _appSettingSection = null; 
    private static readonly ConnectionStringsSection _connectionStringSection = null; 
    private const string CONFIG_PATH = @"..\..\..\The rest of your path\web.config"; 

    static ConfigManager() 
    { 
     ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap() 
     { 
      ExeConfigFilename = CONFIG_PATH 
     }; 

     Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); 

     _clientSection = config.GetSection("system.serviceModel/client") as ClientSection; 
     _appSettingSection = config.AppSettings; 
     _connectionStringSection = config.ConnectionStrings; 
    } 

    public string GetClientEndpointConfigurationName(Type t) 
    { 
     string contractName = t.FullName; 
     string name = null; 

     foreach (ChannelEndpointElement c in _clientSection.Endpoints) 
     { 
      if (string.Compare(c.Contract, contractName, true) == 0) 
      { 
       name = c.Name; 
       break; 
      } 
     } 

     return name; 
    } 

    public string GetAppSetting(string key) 
    { 
     return _appSettingSection.Settings[key].Value; 
    } 

    public string GetConnectionString(string name) 
    { 
     return _connectionStringSection.ConnectionStrings[name].ConnectionString; 
    } 
} 

用法:

ConfigManager mgr = new ConfigManager(); 

string setting = mgr.GetAppSetting("AppSettingKey"); 
string connectionString = mgr.GetConnectionString("ConnectionStringName"); 
string endpointConfigName = mgr.GetClientEndpointConfigurationName(typeof(IServiceContract)); 
+0

我试过了。这基本上可以用来通过一些绝对路径给这两个应用程序相同的配置文件吗? – 2011-04-21 21:21:31

+0

我从来没有尝试过,但我不明白为什么不呢?有趣的想法! – BrandonZeider 2011-04-21 21:22:58