为. dll加载app.config以获取WCF设置
本文关键字:获取 WCF 设置 config dll 加载 app | 更新日期: 2023-09-27 18:14:35
我有一个调用WCF服务的. dll。DLL由一个单独的程序加载,该程序对DLL进行方法调用,DLL通过在方法签名中传递的标志来决定是否使用WCF。当我在应用程序中有WCF绑定信息时,这正常工作,但我不想在应用程序中放置WCF绑定信息。我在我的.DLL中尝试了以下操作,以从DLL的app.config中获取WCF绑定信息,但每次尝试时,我都会得到以下错误:
找不到名称为"Service"和契约为"Service"的端点元素。ServiceModel客户端配置部分中的IService'。这可能是因为没有找到您的应用程序的配置文件,或者因为在客户端元素中没有找到与此名称匹配的端点元素。
这是我用来尝试从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);
虽然我觉得这有点像黑客,但我能够使用以下代码从. dll的配置文件中获得端点/连接字符串。感谢这里的答案:
以编程方式添加端点
:
如何以编程方式更改端点's身份配置?
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);
将端点配置从DLL配置复制到应用程序配置文件。应用程序无法读取DLL配置文件。