Home > Articles

  • Print
  • + Share This
This chapter is from the book

8.6 Choosing Implementations at Runtime

Instead of hard-coding the service URL in client code, you can add it to the application's XML configuration file. For Web applications, this is the web.config file that's in the application's vroot or the folder where your Web form is located. For all other application types, it's a file with the same name as the main application's executable, but with a .config extension. For example, if your Windows application is called myapp.exe, the configuration file is called mayapp.exe.config and resides in the same folder as myapp.exe. The application's configuration file has an <appSettings> section where you can add your own configuration information. For example, if you know the Web service's URL, you can add it like this:

   <add key="WSUrl" value="http://hostname/service.asmx" />

At runtime, you use System.Configuration.ConfigurationSettings to read the URL from the config file:

theProxy.Url= _ 
   System.Configuration.ConfigurationSettings _
  .AppSettings ("WSUrl")

Instead of writing this code yourself, when you run wsdl.exe to generate the proxy class, use the /appsettingurlkey switch like this:

wsdl.exe /l:VB /out:proxy.vb http://localhost/service.asmx?wsdl 

where urlkeyname is the name you used for the Web service URL configuration key, (WSUrl in this example). Alternatively, if you add a Web reference with VS .NET, select the Web reference and open its properties. Change the URL Behavior property to Dynamic (default is Static). The resulting proxy class contains the code to read from AppSettings as shown in Listing 8.16.

Listing 8.16 The proxy class generated by wsdl.exe reads from AppSettings in the constructor

Public Sub New()
    Dim urlSetting As String = _ 
      System.Configuration.ConfigurationSettings.AppSettings( _ 
    If (Not (urlSetting) Is Nothing) Then
        Me.Url = String.Concat(urlSetting, "")
        Me.Url = _ 
    End If
End Sub

As a rule, you should not leave the Web service URL hard-coded in a production client. By making it configurable, you can avoid client recompilation, testing, and deployment when the Web service URL changes.

  • + Share This
  • 🔖 Save To Your Account