【问题标题】:How to instantiate a WCF DataServices Client without hard-coding the URI如何在不硬编码 URI 的情况下实例化 WCF DataServices 客户端
【发布时间】:2011-03-08 07:38:41
【问题描述】:

我对 WCF DataServices (OData) 还很陌生,我需要知道在客户端上实例化实体容器而不对 URI 进行硬编码的最佳方法。似乎 MSDN 上的所有示例都描述了像这样实例化客户端:

Uri uri = new Uri("http://www.someservice.svc");
DataServiceContext svc = new DataServiceContext(uri);

但是,我知道我一定在某个地方遗漏了一些东西,因为像这样硬编码服务地址没有任何意义。一方面,当您从开发到测试再到 QA 再到生产时,当每个环境可能有不同的 URI 时,如何动态更改地址?

感谢您对此的任何见解。

【问题讨论】:

    标签: wcf wcf-client wcf-data-services odata


    【解决方案1】:

    将您的 DataService URL 放入例如你的Settings 文件或只是简单的app.config

    Uri uri = new Uri(ConfigurationManager.AppSettings["ServiceURI"]);
    DataServiceContext svc = new DataServiceContext(uri);
    

    在您的app.config(或web.config 用于网络应用)中:

    <appSettings>
      <add key="ServiceURI" value="http://www.someservice.svc" />
    </appSettings>
    

    或者从数据库配置表中获取它..... or or or or or or..... 有很多选择!

    URI 只是一个字符串 - 您可以从几乎任何您可能拥有的配置源中获取它。

    【讨论】:

    • 我想到了 - 只是把它放在 AppSettings 中,但我认为必须有一个更“以框架为中心”的方法来解决这个问题。在接受您的回答之前,我会稍等片刻,看看是否有其他人提出更好的方法,但可能就是这样。
    【解决方案2】:

    如果您正在使用 Silverlight 应用程序,您可以使用 application.current.host 访问 xap 的 Uri
    然后你可以添加一个相对的Uri来获取服务Uri:

    Uri base = application.current.host; Uri relService = new Uri("..\someservice.svc", System.UriKind.Relative);

    Uri service = new Uri(base, relService); DataServiceContext svc = new DataServiceContext(service);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-07
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2018-08-18
      • 2014-08-23
      相关资源
      最近更新 更多