首页 > 解决方案 > 引用服务时如何使用 dll 的 .config 文件?

问题描述

我知道如果 a 中的代码.dll想要读取其配置文件,则必须手动执行。但是如果(在同一个地方.dll)你引用一个服务,那会搭建一些代码并向.config文件添加一些配置,所以我能够使用该服务的唯一方法就是将该配置复制到主应用程序的.config文件中。

我想知道是否有人有其他方法。我认为它应该使用脚手架提供的任何构造函数,但无法使其工作。

这些是构造函数:

MyServiceClient(string endpointConfigurationName)
MyServiceClient(string endpointConfigurationName, string remoteAddress)
MyServiceClient(string endpointConfigurationName, EndpointAddress remoteAddress)
MyServiceClient(Binding binding, EndpointAddress remoteAddress)

和配置:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicEndPoint" />
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="<service-url>"
          binding="basicHttpBinding" bindingConfiguration="BasicEndPoint"
          contract="<contract>" name="BasicEndPoint" />
    </client>
</system.serviceModel>

提前致谢!

标签: c#

解决方案


当我遇到同样的问题时,我使用了最后一个构造函数:
MyServiceClient(Binding binding, EndpointAddress remoteAddress). 在类构造函数中将服务 uri 作为参数传递,然后只使用默认设置:

private MyServiceClient = _service;

public MyClass(string serviceUri)
{
    if (string.IsNullOrEmpty(serviceUri))
    {
        _service = new MyServiceClient();
    }
    else
    {
        var binding = new System.ServiceModel.BasicHttpBinding() { MaxReceivedMessageSize = int.MaxValue };
        var endpoint = new System.ServiceModel.EndpointAddress(serviceUri);
        _service = new MyServiceClient (binding, endpoint);
    }
}

但是,我不知道您可以按照Marc_s 的回答(也在 dotnetstep 的评论中链接)中演示的那样将配置文件外部化 - 如果我知道这一点,我可能会改用它。

顺便说一句,请注意,在我的代码中,如果您传递 null 或空字符串,serviceModel则应在配置文件中找到。


推荐阅读