开发者

configSource absolute path work-around

I have a WCF data service with some methods I call asynchronously during page_load events.

I need a solution to call these methods from either a script or console app if necessary.

I created a console app that references the WCF .dll libraries. I have to duplicate some of the configuration variables that are in web.config under the WCF service into an app.config under the console app.

I want the app.config to mirror the web.config automatically or somehow point the console app at the WCF services web.config.

My console app and wcf projects are adjacent to eachother in the same solution, so the 'configSource' attribute wont work. No parent directories or absolute paths are allowed.

Does anyone know of a work-aroun开发者_如何学Cd for this?


Ok, I don't know what your custom config section is, but this class will show you how to retrieve config sections (system.serviceModel/client in this example), app settings and connection strings programmatically. You should be able to modify it to fit your needs.

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;
    }
}

Usage:

ConfigManager mgr = new ConfigManager();

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜