加载.DLL的app.config获取WCF设置

时间:2016-10-24 18:54:45

标签: c# wcf dll

我有一个.DLL来调用WCF服务。 DLL由一个单独的程序加载,该程序对DLL进行方法调用,DLL决定是否通过方法签名中传递的标志使用WCF。当我在应用程序中有WCF绑定信息时,这通常正常工作,但我不想将WCF绑定信息放在应用程序中。我在我的.DLL中尝试了以下内容,以从DLL的app.config中获取WCF绑定信息,但每次尝试时,都会出现以下错误:

  

无法找到名称为'服务'的端点元素和合同' Service.IService'在ServiceModel客户端配置部分中。这可能是因为没有为您的应用程序找到配置文件,或者因为在客户端元素中找不到与此名称匹配的端点元素。

以下是我用来尝试从DLL的app.config获取WCF绑定/设置的代码:

        private static readonly Configuration Config = LoadWCFConfiguration();

    public void CreateOpsConnection (AccountingOpConnectionDTO opsConnectionDTOFromCaller, bool UseWCFValue)
    {
        opsConnectionDTO = opsConnectionDTOFromCaller;
        UseWCF = UseWCFValue;

        if (UseWCF == true)
        {

            ConfigurationChannelFactory<AccountingOpsServiceReference.IAccountingOperationsService> accountingOpsChannelFactory = new ConfigurationChannelFactory<AccountingOpsServiceReference.IAccountingOperationsService>
            ("AccountingOperationsService", Config, null);
            WCFClient = accountingOpsChannelFactory.CreateChannel();
            //WCFClient = new AccountingOpsServiceReference.AccountingOperationsServiceClient();
            WCFClient.CreateConnection(opsConnectionDTO);

2 个答案:

答案 0 :(得分:0)

将端点配置从DLL配置复制到应用程序配置文件。应用程序无法读取DLL配置文件。

答案 1 :(得分:0)

虽然我觉得这有点像黑客,但我能够使用以下代码从.DLL的配置文件中获取端点/连接字符串。感谢位于此处的答案:

Programatically adding an endpoint

在这里:

How to programmatically change an endpoint's identity configuration?

        private static string LoadWCFConfiguration()
    {
        XmlDocument doc = null;
        Assembly currentAssembly = Assembly.GetCallingAssembly();
        string configIsMissing = string.Empty;
        string WCFEndPointAddress = string.Empty;
        string NodePath = "//system.serviceModel//client//endpoint";

        try
        {
            doc = new XmlDocument();
            doc.Load(Assembly.GetEntryAssembly().Location + ".config");
        }
        catch (Exception)
        {

            configIsMissing = "Configuration file is missing for Manager or cannot be loaded. Please create or add one and try again.";

            return configIsMissing;
        }

        XmlNode node = doc.SelectSingleNode(NodePath);

        if (node == null)
            throw new InvalidOperationException("Error. Could not find the endpoint node in config file");

        try
        {
            WCFEndPointAddress = node.Attributes["address"].Value;
        }
        catch (Exception)
        {

            throw;
        }

        return WCFEndPointAddress;
    }

后记唯一要做的就是使用上述方法返回的端点地址实例化客户端对象:

System.ServiceModel.BasicHttpBinding binding = new System.ServiceModel.BasicHttpBinding();

System.ServiceModel.EndpointAddress endpoint = new System.ServiceModel.EndpointAddress(new Uri(wcfEndpoint));

            WCFClient = new ServiceReference.ServiceClient(binding, endpoint);