Windows服务中托管WCF服务的简化指南

在本教程中,将学习如何在Windows服务托管WCF服务。Windows服务托管适用于长时间运行的WCF服务,其中服务的生命周期由操作系统控制。在之前的WCF教程中,已经实现了在控制台应用程序中的WCF自托管,现在将按照逐步的方法来托管WCF服务。

创建WCF服务的类库

在Visual Studio中,创建一个新的类库项目,命名为“StudentService”,然后添加一个新的“WCF服务”到这个类库项目中。这将添加服务契约(IStudentService)及其实现类(StudentService)到类库项目中,并添加对System.ServiceModel的引用。

IStudentService接口的代码如下:

public interface IStudentService { string GetStudentInfo(int studentId); }

StudentService实现类的代码如下:

public class StudentService : IStudentService { public string GetStudentInfo(int studentId) { string studentName = string.Empty; switch (studentId) { case 1: studentName = "Muhammad Ahmad"; break; case 2: studentName = "Muhammad Hamza"; break; default: studentName = "No student found"; break; } return studentName; } }

添加Windows服务

为了在Windows服务中托管这个WCF服务,让向解决方案中添加一个新的Windows服务项目“WinServiceStudentHost”。Windows服务将引用StudentService类库和System.ServiceModel。

在Windows服务的OnStart()方法中编写WCF服务托管代码,并在OnStop()方法中相应地关闭服务。

public partial class StudentHost : ServiceBase { ServiceHost studentServiceHost = null; public StudentHost() { InitializeComponent(); } protected override void OnStart(string[] args) { try { Uri httpBaseAddress = new Uri("http://localhost:4321/StudentService"); studentServiceHost = new ServiceHost(typeof(StudentService.StudentService), httpBaseAddress); studentServiceHost.AddServiceEndpoint(typeof(StudentService.IStudentService), new WSHttpBinding(), ""); ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior(); serviceBehavior.HttpGetEnabled = true; studentServiceHost.Description.Behaviors.Add(serviceBehavior); studentServiceHost.Open(); } catch (Exception ex) { studentServiceHost = null; } } protected override void OnStop() { if (studentServiceHost != null) { studentServiceHost.Close(); studentServiceHost = null; } } }

不要忘记使用System.ServiceModel和System.ServiceModel.Description命名空间。

安装Windows服务

为了安装Windows服务,需要向项目中添加一个安装程序类。右键点击Windows服务项目WinServiceStudentHost,选择添加->新建项->安装程序类。

Host Installer类的代码如下:

[RunInstaller(true)] public partial class StudentHostInstaller : System.Configuration.Install.Installer { public StudentHostInstaller() { ServiceProcessInstaller process = new ServiceProcessInstaller(); process.Account = ServiceAccount.NetworkService; ServiceInstaller service = new ServiceInstaller(); service.ServiceName = "StudentHostWindowService"; service.DisplayName = "StudentHostWindowService"; service.Description = "Student WCF Service Hosted Successfully."; service.StartType = ServiceStartMode.Automatic; Installers.Add(process); Installers.Add(service); } }

不要忘记使用System.ServiceProcess命名空间。

沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485