基于 C# .NET Framework 4.0 开发实现 WCF 服务实例详解(二)——实现Windows服务内嵌WCF服务

目录

引言

[1. 创建一个新的Windows服务项目](#1. 创建一个新的Windows服务项目)

[2. 添加WCF服务](#2. 添加WCF服务)

[2.1 添加服务接口和实现](#2.1 添加服务接口和实现)

[2.2 添加服务配置](#2.2 添加服务配置)

[3. 实现Windows服务](#3. 实现Windows服务)

[3.1 修改Service1类](#3.1 修改Service1类)

[3.2 在项目中添加ServiceInstaller](#3.2 在项目中添加ServiceInstaller)

[4. 安装和运行Windows服务](#4. 安装和运行Windows服务)

[4.1 编译项目](#4.1 编译项目)

[4.2 使用InstallUtil.exe安装服务](#4.2 使用InstallUtil.exe安装服务)

[4.3 启动服务](#4.3 启动服务)

[5. 测试WCF服务](#5. 测试WCF服务)

[5.1 添加客户端应用程序](#5.1 添加客户端应用程序)

[5.2 添加服务引用](#5.2 添加服务引用)

[5.3 调用服务](#5.3 调用服务)

[6. 卸载Windows服务](#6. 卸载Windows服务)


引言

我们利用C#可以快速开发各种后端服务,如常见的windows服务、WCF 服务、WebService服务、WebApi等,上一篇文章介绍了简单WCF服务的实现,本文将详细讲解如何基于 C# 和 .NET Framework 4.0 将 WCF服务和宿主项目合并到同一个项目中,并将其安装为Windows服务,确保每个步骤都清晰且易于理解和掌握。

以下是详细的步骤:

1. 创建一个新的Windows服务项目

  1. 打开Visual Studio,创建一个新的项目。
  2. 选择 Windows Service 项目类型,命名为 WcfWindowsService

2. 添加WCF服务

2.1 添加服务接口和实现

在项目中添加两个类:IService1.csService1.cs

IService1.cs:

cs 复制代码
using System.ServiceModel;

namespace WcfWindowsService
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);
    }
}

Service1.cs:

cs 复制代码
namespace WcfWindowsService
{
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return $"You entered: {value}";
        }
    }
}
2.2 添加服务配置

在项目中添加一个 App.config 文件,并添加以下配置:

XML 复制代码
<configuration>
  <system.serviceModel>
    <services>
      <service name="WcfWindowsService.Service1">
        <endpoint address="" 
                  binding="basicHttpBinding" 
                  contract="WcfWindowsService.IService1" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/WcfWindowsService/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" />
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

3. 实现Windows服务

3.1 修改Service1类

Service1.cs 文件中创建一个新的类 WcfService,继承自 ServiceBase 类:

cs 复制代码
using System;
using System.ServiceModel;
using System.ServiceProcess;

namespace WcfWindowsService
{
    public partial class WcfService : ServiceBase
    {
        public ServiceHost serviceHost = null;

        public WcfService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            serviceHost = new ServiceHost(typeof(Service1));
            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}
3.2 在项目中添加ServiceInstaller
  1. 右键点击项目,选择 Add -> New Item
  2. 选择 Component Class,命名为 ProjectInstaller.cs

ProjectInstaller.cs 中实现服务安装:

cs 复制代码
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace WcfWindowsService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller processInstaller;
        private ServiceInstaller serviceInstaller;

        public ProjectInstaller()
        {
            processInstaller = new ServiceProcessInstaller();
            serviceInstaller = new ServiceInstaller();

            // 设置服务使用的账号类型
            processInstaller.Account = ServiceAccount.LocalSystem;

            // 设置服务信息
            serviceInstaller.ServiceName = "WcfWindowsService";
            serviceInstaller.DisplayName = "WCF Windows Service";
            serviceInstaller.StartType = ServiceStartMode.Manual;

            Installers.Add(processInstaller);
            Installers.Add(serviceInstaller);
        }
    }
}

4. 安装和运行Windows服务

4.1 编译项目

确保项目没有错误,然后编译项目。

4.2 使用InstallUtil.exe安装服务

打开管理员权限的命令提示符,导航到编译输出目录(通常是bin\Debug或bin\Release),并运行以下命令以安装服务:

bash 复制代码
installutil WcfWindowsService.exe
4.3 启动服务
  1. 打开 Services 管理器(按下Win+R,输入 services.msc 后回车)。
  2. 找到名为 WcfWindowsService 的服务。
  3. 右键点击服务,选择 Start 启动服务。

5. 测试WCF服务

5.1 添加客户端应用程序
  1. 创建一个新的 Console Application 项目来测试服务,命名为 WcfClient
5.2 添加服务引用

在客户端项目中,右键点击项目,选择 Add Service Reference,输入服务地址(如 http://localhost:8733/Design_Time_Addresses/WcfWindowsService/Service1/),然后点击 GoOK

5.3 调用服务

在客户端的 Program.cs 中调用服务:

cs 复制代码
using System;

namespace WcfClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new ServiceReference1.Service1Client();
            string result = client.GetData(42);
            Console.WriteLine(result);
            client.Close();
        }
    }
}

6. 卸载Windows服务

如果不再需要服务,可以卸载:

bash 复制代码
installutil /u WcfWindowsService.exe

通过这些步骤,您可以将WCF服务和宿主项目合并到同一个项目中,并将其安装为Windows服务。这样可以实现WCF服务的长期运行,并通过Windows服务管理器来管理服务的生命周期。

相关推荐
小飞侠在吗19 分钟前
Windows 下 Nginx 访问 127.0.0.1 报 50x 错误:根因是路径里 \t 被当成 Tab
运维·windows·nginx
longxiaozhang61 小时前
C#运算符重载:让对象也能使用“加减乘除”
开发语言·c#
花落人散处2 小时前
C# 核心编程知识点总结:网络编程、委托与事件、异步编程与LINQ
c#
水饺编程4 小时前
第5章,[Win32 章节] :贝塞尔样条曲线(一)
c语言·c++·windows·visual studio
fl1768315 小时前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
辻弋2015 小时前
一键优化电源计划、游戏模式、独显强制、禁用后台录制——DeltaForceBooster专治三角洲行动卡顿掉帧,所有改动可一键还原
服务器·数据库·windows·游戏·电脑·php
言乐66 小时前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
深念Y6 小时前
OnlyOffice 打开来自 Windows/WPS 的 Office 文档时,出现排版错乱、文字空白、字体显示异常。
linux·windows·debian·onlyoffice·字体·wps·office
CoderIsArt6 小时前
OPC UA 完整介绍、官网、C# 简单使用
开发语言·c#
易点云徐源6 小时前
(已解决)adb devices 不显示设备,但 Windows 的 ADB Interface 正常:一次 WinUSB 与旧版 ADB 兼容性排查实战
windows·adb