在WPF客户端引用WCF服务项目程序集和System.ServiceModel程序集,如果需要读取配置文件则引用System.Configuration程序集。
在App.cs 文件中相应的方法添加相应的启动服务方法,整体示例代码如下:
private MainWindow mainWindow;private ServiceHost Host = null;
static App()
Unknown macro: { //MVVM多线程UI处理帮助类。 // DispatcherHelper.Initialize(); }
/// <summary>/// 引发Startup事件/// </summary>/// <param name="e">启动参数</param>protected override void OnStartup(StartupEventArgs e)
Unknown macro: { base.OnStartup(e); Init(); }
/// <summary>/// 初始化/// </summary>private void Init(){try{//服务启动后才能跳转到主应用程序if (StartServers())
Unknown macro: { InitMainWindow(); }
}catch (Exception ex)
Unknown macro: { //记录日志 }
}
/// <summary>/// 启动WCF服务/// </summary>private bool StartServer(){if (Host == null){try{Host = new ServiceHost(typeof(WcfService1.Service1));
//绑定System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();//终结点Host.AddServiceEndpoint(typeof(WcfService1.IService1), httpBinding, ":18492/");if (Host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null)
Unknown macro: { //行为 ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; //元数据地址 behavior.HttpGetUrl = new Uri("http}
}catch (Exception ex)
Unknown macro: { //记录日志 return false; }
}return true;}
/// <summary>/// 启动WCF服务,,重app.config文件中读取配置信息/// </summary>private bool StartServers(){if (Host == null){try{Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
foreach (ServiceElement el in svcmod.Services.Services)
Unknown macro: { string typeName = el.Name + "," + el.Name.Substring(0,el.Name.LastIndexOf(‘.’)); Type svcType = Type.GetType(typeName); if (svcType == null) throw new Exception("Invalid Service Type " + el.Name + " in configuration file."); Host = new ServiceHost(svcType); Host.Open(); }
}catch (Exception ex)
Unknown macro: { //记录日志 return false; }
}return true;}
/// <summary>/// 程序退出/// </summary>/// <param name="e"></param>protected override void OnExit(ExitEventArgs e)
Unknown macro: { base.OnExit(e); CloseHost(); }
/// <summary>/// 关闭服务。/// </summary>private void CloseHost(){if (Host != null)
Unknown macro: { Host.Close(); }
}
/// <summary>/// 初始化应用程序主窗口/// </summary>private void InitMainWindow()
Unknown macro: { mainWindow = new MainWindow(); }
困难与折磨对于人来说,是一把打向坯料的锤,