silverlight动态创建WCF服务
生活随笔
收集整理的這篇文章主要介紹了
silverlight动态创建WCF服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?最近在發布silverlight項目時,服務地址不是固定,因此服務需要動態創建。在網上搜了點資料找到了動態創建服務的方法,直接上代碼
/// <summary>/// 根據服務類型創建服務/// </summary>public static class CreateService{#region//動態創建服務/// <summary>/// 動態創建基本服務/// </summary>/// <typeparam name="serviceType">服務類型</typeparam>/// <returns></returns>public static T GetBasicService<T>(string serviceType) where T : class{T instance = null;BasicHttpBinding bhb = new BasicHttpBinding();string address = GetServerUrl(serviceType);EndpointAddress endPointAddress = new EndpointAddress(address);object[] paras = new object[2];paras[0] = bhb;paras[1] = endPointAddress;ConstructorInfo constructor = null;try{Type[] types = new Type[2];types[0] = typeof(System.ServiceModel.Channels.Binding);types[1] = typeof(System.ServiceModel.EndpointAddress);constructor = typeof(T).GetConstructor(types);}catch (Exception){}if (constructor != null)instance = (T)constructor.Invoke(paras);return instance;}/// <summary>/// 根據服務類型新建一個自定義服務實例/// </summary>/// <param name="serviceType">服務類型</param>/// <returns></returns>public static T GetCustomerService<T>(string serviceType) where T : class{T _instance = null;string serviceUri = GetServerUrl(serviceType);if (string.IsNullOrEmpty(serviceUri)) return null;object[] paras = new object[2];var elements = new List<BindingElement>();elements.Add(new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.Default, WriteEncoding = Encoding.UTF8 });HttpTransportBindingElement bindingElement = new HttpTransportBindingElement();bindingElement.MaxReceivedMessageSize = int.MaxValue;bindingElement.MaxBufferSize = int.MaxValue;elements.Add(bindingElement);CustomBinding binding = new CustomBinding(elements);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] = typeof(System.ServiceModel.EndpointAddress);constructor = typeof(T).GetConstructor(types);}catch (Exception){return null;}if (constructor != null)_instance = (T)constructor.Invoke(paras);return _instance;}#endregion#region//獲取當前服務的地址/// <summary>/// 獲取當前服務的URL/// </summary>/// <returns></returns>private static string GetServerUrl(string serviceName){return App.ServiceUriList[serviceName];}#endregion}
轉載于:https://www.cnblogs.com/HellenTian/archive/2011/08/31/2160430.html
總結
以上是生活随笔為你收集整理的silverlight动态创建WCF服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 引擎战斗效果截图2
- 下一篇: 当众讲话第二章当众讲话的基本原则