How to dynamically set the WCF Service address in the Silverlight Program

Source: Internet
Author: User

This article short address: http://zdd.me/slwcfendpoint

After a service reference is added to the Silverlight project, a ServiceReferences is generated in the Silverlight project. clientConfig file, which contains the bindings and Endpoint configurations of the referenced service. The following is the configuration information automatically generated after referencing a WCF Service:

<configuration>    <system.serviceModel>        <bindings>            <basicHttpBinding>                <binding name="BasicHttpBinding_IService1" maxBufferSize="2147483647"                    maxReceivedMessageSize="2147483647">                    <security mode="None" />                </binding>            </basicHttpBinding>        </bindings>        <client>            <endpoint address="http://localhost:4177/Services/Service1.svc"                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"                contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />        </client>    </system.serviceModel></configuration>

In the program development stage, there will be no errors when the above configuration information is used. When deploying a program, the service address is usually different from the service address used during development. In this case, you need to modify the endpoint address in the configuration information above. However, after the Silverlight project is compiled, ServiceReferences. ClientConfig is embedded into the generated xap file, which makes modification difficult. Tim Heuer, the address for dynamically setting service endpoints, describes several methods in Managing service references and endpoint endpoints for Silverlight applications (http://zdd.me/managingendpoint) for your reference. The following two methods are used in the development process.

I. WCF and Silverlight are located at the same site

In this case, you can obtain the service address through the Application. Current. Host. Source of the Silverlight program and the relative address of the service. For example, if a service named Service1.svc is placed in the Services folder of a website, you can obtain its address using the following code:

Uri serviceUri = new Uri(Application.Current.Host.Source, "../Services/Service1.svc")

Then, you can reload the constructor of the client proxy class automatically generated when you reference the service.

public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :                 base(binding, remoteAddress) {        } 

To create a new instance of this type

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);            binding.MaxReceivedMessageSize = int.MaxValue;            binding.MaxBufferSize = int.MaxValue;            ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(binding, new EndpointAddress(                new Uri(Application.Current.Host.Source, "../Services/Service1.svc")));

2. WCF is located under a separate site

In this case, the WCF address is different from the website address, so you cannot use the above method. In this case, you can configure the service address in the web. config of the website, and then transmit the service address to the Silverlight program through the InitParams parameter of Silverlight. The implementation method is as follows:
1. Configure the service address in web. config.

<Deleetask>
<! -- Format service name svc -->
<Add key = "Service1svc" value = "http: /localhost: 1468/Service1.svc"/>
</AppSettings>

2. Use the Literal control to dynamically generate the InitParams parameter of Silverlight

Then, retrieve the configured service address from web. config in Page_Load on the webpage and set the value of the InitParams parameter.

protected void Page_Load(object sender, EventArgs e)        {            if (!Page.IsPostBack)            {                Hashtable services = new Hashtable();                foreach (string key in ConfigurationManager.AppSettings.AllKeys)                {                    if (key.EndsWith("svc", StringComparison.CurrentCultureIgnoreCase))                    {                        services.Add(key,ConfigurationManager.AppSettings[key]);                    }                }                StringBuilder sb = new StringBuilder();                foreach (string key in services.Keys)                {                    sb.Append(string.Format(",{0}={1}", key, services[key]));                }                this.SLInitParams.Text = string.Format("<param name=\"InitParams\" value=\"{0}\" />", sb.ToString());            }        }

3. In the Application_Startup of Silverlight, store the values in the parameter in ResourceDictionary for future use. Add a ServiceType enumeration in the Silverlight project to list the key values of all service addresses configured in web. config.

4. Create a New ServiceHelper generic class. This class includes two static methods: 1) GetInstance accepts a ServiceType type parameter and creates an instance of the client proxy class of the service through reflection; 2) getServiceAddress also accepts a ServiceType type parameter to obtain the service address.

Public class ServiceHelper <T> where T: class {// <summary> // create a service instance based on the service type // </summary> // <param name = "serviceType"> service type </ param> // <returns> </returns> public static T GetInstance (ServiceType serviceType) {T _ instance = null; string serviceUri = GetServiceAddress (serviceType); if (string. isNullOrEmpty (serviceUri) return null; object [] paras = new object [2]; BasicHttpBinding binding = n Ew BasicHttpBinding (BasicHttpSecurityMode. none); binding. maxBufferSize = int. maxValue; binding. maxcompute edmessagesize = int. maxValue; EndpointAddress address = new EndpointAddress (new Uri (serviceUri, UriKind. absolute); paras [0] = binding; paras [1] = address; ConstructorInfo constructor = null; try {Type [] types = new Type [2]; types [0] = typeof (System. serviceModel. channels. binding); types [1] = ty Peof (System. ServiceModel. EndpointAddress); constructor = typeof (T). GetConstructor (types);} catch (Exception) {return null;} if (constructor! = Null) _ instance = (T) constructor. invoke (paras); return _ instance ;} /// <summary> /// obtain the service address /// </summary> /// <param name = "serviceType"> service type </param> /// <returns> </returns> public static string GetServiceAddress (ServiceType serviceType) {return App. current. resources [serviceType. toString ()]. toString ();}}

Then you can use the following code to create a client proxy instance of the service.

 

The example program downloads slwcfserviceendpoints.zip

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.