configSource绝对路径解决方案

本文关键字:解决方案 路径 configSource | 更新日期: 2023-09-27 17:52:33

我有一个WCF数据服务,其中一些方法我在page_load事件期间异步调用。

如果需要的话,我需要一个解决方案来从脚本或控制台应用程序调用这些方法。

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

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

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

有谁知道解决这个问题的方法吗?

configSource绝对路径解决方案

好吧,我不知道你的自定义配置节是什么,但是这个类将向你展示如何检索配置节(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));

相关文章: