Silverlight:如何在放置在xap中时设置ServiceReferences.ClientConfig

14 silverlight wcf

我正在使用我的silverlight应用程序的wcf服务.wcf服务的位置在ServiceReferences.ClientConfig文件中声明,并且必须更改为安装应用程序的位置.

但是,此文件包含在xap文件中,并且在部署应用程序时不能轻易更改.是否有另一种方法从silverlight应用程序中引用wcf服务?或者,如何更改xap文件中的ServiceReferences.ClientConfig?

Pau*_*lly 8

可能有更好的方法,我可以使用,但这对我有用,而且很灵活.

在Web应用程序的Web.config中,在AppSettings中添加一个变量并存储基本URL,注意我没有存储SVC文件的位置,我稍后会附加.这是因为我通常指向多个SVC.您可以选择以不同方式执行此操作.

 <appSettings>
    <add key="ServiceURI" value="http://localhost:64457/"/>
 </appSettings>
Run Code Online (Sandbox Code Playgroud)

在我的Web应用程序的Web页面中,添加一个名为InitParms的参数,这允许您添加一个键,对值列表(由逗号分隔,将由XAP文件读取)

<div id="silverlightControlHost">
    <object data="data:application/x-silverlight," type="application/x-silverlight-2"
        width="100%" height="100%" ID="Xaml1" >
        <param name="InitParams" value="ServiceURI=<%= ConfigurationManager.AppSettings("ServiceURI") %>" />
Run Code Online (Sandbox Code Playgroud)

在Silverlight App.xaml.vb中,将所有InitParms加载到资源或任何您想要的位置

    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup
    If e.InitParams IsNot Nothing Then
        For Each k As Generic.KeyValuePair(Of String, String) In e.InitParams
            Me.Resources.Add(k.Key, k.Value)
        Next
    End If
Run Code Online (Sandbox Code Playgroud)

然后在我的任何XAML文件中,我可以使用配置的URI初始化服务,我有一个像这样的方法

Private Sub InitializeService()
    Dim uri As String = App.Current.Resources("ServiceURI")
    If uri Is Nothing OrElse uri = String.Empty Then
        'if there is no value added in the web.config, I can fallback to default values
        _client = New ServiceClient
    Else
        'Notice I hardcoded the location of the SVC files in the client and append there here, you may choose not to do this
        Dim uri_withservice As String = uri & "svc/secure/Service.svc"
        _client = New ServiceClient("CustomBinding_Service", New EndpointAddress(uri_withservice))
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)


小智 7

很好,有了这些建议,我设法让我的WCF ServiceReferences.ClientConfig数据在应用程序启动时动态更改,从web.config读取服务URI.这可以通过使用VS2010中的"web.config转换"来实现.

这是一个示例web.config.debug,显示当我为我的网站选择"发布"时如何替换ServiceURI.

<?xml version="1.0"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
     <...>
  </connectionStrings>

  <appSettings>
    <add key="ServiceURI" value="http://my.location.com/myService.svc"
         xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
  </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)

在我的基础web.config中,我有相同的键/值,指向本地服务.每次部署到测试/生产时都无需记住更改ServiceURI.太好了,我一直在寻找那一段时间.


小智 2

在这个博客中找到了解决方案。

http://www.andybeaulieu.com/Default.aspx?tabid=67&EntryID=132

这里的wcf服务端点是根据silverlight应用程序的位置计算出来的