2016-10-24 2 views
0

У меня есть .DLL, который вызывает вызовы для службы WCF. DLL загружается отдельной программой, которая вызывает вызовы методов для DLL, и DLL решает, использовать ли WCF флаг, который передается в сигнатурах метода. Это нормально работает, когда у меня есть информация привязки WCF в приложении, но я не хочу, чтобы она привязывала информацию привязки WCF в приложении. Я попытался следующие в моей .DLL, чтобы получить информацию о связывании в WCF из app.config в DLL, но каждый раз, когда я пытаюсь это, я получаю следующее сообщение об ошибке:Загрузка app.config для .DLL Чтобы получить настройки WCF

Could not find endpoint element with name 'Service' and contract 'Service.IService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.

Вот код, я использую для попытаться получить WCF обязательные/настройки из app.config в библиотеки DLL:

 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); 
+1

Вы не можете этого сделать - система .NET config построена на предположении, что только ** основная программа ** (консольное приложение, программа Winforms, веб-сайт) имеет файл конфигурации, который считывается. Не сражайся с ним - прими его и иди с потоком! –

ответ

0

Копирование конфигурации конечных точек из DLL конфигурации в файле конфигурации приложения. Приложение не может прочитать файл конфигурации DLL.

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

Afterwords единственное, что осталось сделать, это создать экземпляр объекта клиента с адресом конечной точки вернулся из выше метода:

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); 
Смежные вопросы