C#WCF:在共享库中有一个app.config,提供对服务的访问

我目前有一个包含几个项目的解决方案,其中一个是WCF服务。 我创建了另一个使用静态类的投影,它基本上为WCF客户端的实例提供了一个网关,如下所示:

public static class WSGateway { public static DBInteractionGatewayClient MR_WebService { get { return new DBInteractionGatewayClient(); } } } 

这是(或者我认为)我可以使用仅在该库中的单个app.config文件,然后其他项目可以只引用它并从该属性获取对该客户端的引用。

但问题是,当一个项目试图访问该属性时,会抛出一个exception,告诉我在应用程序中需要app.config ,当我将app.config复制到我的网关库时,它可以工作。


有没有办法避免在应用程序中有多个app.config文件,并且只有一个可能是一个库?


[更新]解决方案:

按照Anderson Imes的建议,现在我决定对类中的客户端引用配置进行硬编码,从而消除了对多个app.config的需求。

因此,我从这个( app.config )翻译了我的配置:

                     

对此( static class ):

 public static class WSGateway { private static WSHttpBinding binding; private static EndpointAddress endpointAddress; static WSGateway() { var readerQuotas = new XmlDictionaryReaderQuotas() { MaxDepth = 6000000, MaxStringContentLength = 6000000, MaxArrayLength = 6000000, MaxBytesPerRead = 6000000, MaxNameTableCharCount = 6000000 }; binding = new WSHttpBinding(SecurityMode.None) {MaxReceivedMessageSize = 6000000, ReaderQuotas = readerQuotas}; endpointAddress = new EndpointAddress("http://agnt666laptop:28666/DBInteractionGateway.svc"); } public static DBInteractionGatewayClient MR_WebService { get { return new DBInteractionGatewayClient(binding, endpointAddress); } } public static void ExecuteCommand(Action command) { var ws = MR_WebService; command.Invoke(ws); ws.Close(); } } 

您收到该错误的原因是WCF客户端代理的默认构造函数从本地配置中查找通道配置。 您可以通过指定要使用/连接到的绑定和地址来覆盖此行为。

这里有几个选项,每个选项都有不同的部署模型。

  1. 硬编码“网关”库中的端点信息(常见术语是“代理”)。 您只需返回新的DBInteractionGatewayClient(绑定,地址); 对于此解决方案,您只需分发WSGateway代码所在的程序集(以下称为“WSGateway程序集”)。
  2. 创建所有站点都可以访问的公共配置文件。 如果这些都是同一台机器上的所有服务,这很容易做到。 将配置数据放在共享的公共驱动器位置并从那里读取。 如果您希望可以使用可能的WCF配置的全部色域,则需要使用ConfigurationManager.OpenMappedExeConfiguration方法并手动读取它并在打开客户端通道之前手动将其应用于绑定。 为此,您将确保您可以访问集中位置的配置文件并向您分发WSGateway程序集。
  3. 将配置移动到可从所有应用程序(如数据库)访问的公共资源。 这将允许您从解决方案中的任何位置访问此配置数据。 对于此解决方案,您将确保可以从解决方案中的所有点访问配置数据库并分发WSGateway程序集。

这些是我能想到的解决方案。 让我们知道您的决定。

安德烈亚斯的回答以“p”结尾,所以我觉得有些东西没有得到正确的复制和粘贴。 但它让我走上正轨,我想出了这个。 我从MS(计算器)的示例WCF介绍开始。

这是在客户端应用程序上使用app.config的旧方法

  CalculatorClient client = new CalculatorClient(); 

这是不需要app.config的硬编码版本。 我仔细检查了绑定部分中app.config中的所有值都是默认值,不需要显式复制。 但是,您可以将所有这些值直接添加到binding的属性中。

  string address = "http://localhost:8000/ServiceModelSamples/Service/CalculatorService"; WSHttpBinding binding = new WSHttpBinding(); binding.Name = "WSHttpBinding_ICalculator"; // not sure if this is necessary. EndpointAddress endpointAddress = new EndpointAddress(address); CalculatorClient client = new CalculatorClient(binding, endpointAddress); return client; 

顺便说一句,我不知道我在做什么这些绑定,我只是想让它工作! 我昨天刚刚了解了WCF …我想将整个界面放在DLL中,并且不希望将app.config与GUI前端复制或合并。