WCF - Windows Service Hosting

WCF - Windows Service Hosting

The operation of Windows service hosting is a simple one. Given below are the steps with requisite coding and screenshots that explain the process in an easy way.

在windows服务上托管wcf是一个简单的操作。

Step-1: Now let’s create a WCF service. Open Visual Studio 2008 and click New → Project and select Class Library from the template.

Step-2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service.

Step-3: Next, we can create the ISimpleCalculator interface. Add the Service and Operation Contract attribute as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace WCFHostedWindowsService
{
    [ServiceContract]
    interface ISimpleCalculator
    {
        [OperationContract]
        int Sum(int number1, int number2);

        [OperationContract]
        int Subtract(int number1, int number2);

        [OperationContract]
        int Multiply(int number1, int number2);

        [OperationContract]
        double Divide(int number1, int number2);
    }
}

Step-4: Implement the ISimpleCalculator interface as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WCFHostedWindowsService
{
    class SimpleCalculator : ISimpleCalculator
    {
        public int Sum(int number1, int number2)
        {
            return number1 + number2;
        }

        public int Subtract(int number1, int number2)
        {
            return number1 - number2;
        }

        public int Multiply(int number1, int number2)
        {
            return number1 * number2;
        }

        public double Divide(int number1, int number2)
        {
            if (number2 != 0)
            {
                return number1 / number2;
            }
            else
            {
                return 0;
            }
        }
    }
}

Step-5: Build the Project and get the dll. Now, we are ready with the WCF service. We are going to see how to host the WCF service in Windows service.

Note: In this project, it is mentioned that we are creating both Contract and Service (implementation) in the same project. However it is always a good practice if you have both in different projects.

Step-6: Open Visual Studio 2008 and Click New → Project and select Windows Service.

Step-7: Add ‘WindowsServiceHostedService.dll‘ as reference to the project. This assembly is going to act as service.

Step-8: The OnStart method of the service can be used to write the hosting code for WCF. We have to make sure that we are using only one service host object. OnStop method is used to close the Service Host. The following code shows how to host the WCF service in Windows service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;
using WindowsServiceHostedService;

namespace WCFHostedWindowsService
{
    class WCFHostedWindowsService : ServiceBase
    {
        ServiceHost serviceHost;

        public WCFHostedWindowsService()
        {
            InitializeComponent();
        }

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

            //Create a URI to serve as the base address
            Uri httpUrl = new Uri("http://localhost:8090/WindowsServiceHostedService/SimpleCalculator");

            //Create ServiceHost
            serviceHost = new ServiceHost(typeof(SimpleCalculator), httpUrl);

            //Add a service endpoint
            serviceHost.AddServiceEndpoint(typeof(ISimpleCalculator), new WSHttpBinding(), "");//ISimpleCalulator  //ISimpleCalulator

            //Enable metadata exchange
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(smb);

            //Start the Service
            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "Service1";
        }

        #endregion
    }
}

Step-9: In order to install the service, we need to have the Installer class for the Windows service. So add a new Installer class to the project, which is inherited from the Installer class. Given below is the code that shows the Service name, StartUp type, etc. of the service.

Step-10: Build the project to get the executable file WCFHostedWindowsService.exe. Next, we need to install the service using the Visual Studio Command Prompt.

So open the command prompt by clicking Start→All Programs→Microsoft Visual Studio 2008→Visual Studio Tools→ Visual Studio Command Prompt. Using the install util utility application, you can install the service as shown below.

时间: 2024-10-28 15:41:43

WCF - Windows Service Hosting的相关文章

WCF Windows Service Using TopShelf and ServiceModelEx z

http://lourenco.co.za/blog/2013/08/wcf-windows-service-using-topshelf-and-servicemodelex/ There are two excellent .NET libraries that help us to build enterprise solutions using the Windows Communication Foundation (WCF) – TopShelf and ServiceModelEx

WCF: Hosting WCF in Windows Service

1. Create a windows service project 2. Add Reference to the assembly which contains the contract and its implementation. 3. Remove the Service1.cs, add a new Windows Service class and name it to CalculatorWindowsService 4. Override OnStart and OnStop

WCF注册Windows Service

WCF注册Windows Service 2014-06-14 返回 在前面创建一个简单的WCF程序,我们把WCF的服务寄宿到了Host这个控制台项目中了.下面将介绍如何把WCF的服务寄宿到Windows服务中: 1. 删除原来Host控制台项目,然后在solution上右键,新建一个WindowService项目.如下图: 2.对MyFirstWindowsService项目添加对Contracts项目.Service项目和System.ServiceModel的引用. 3.将MyFristW

Hosting Web API in Windows service

Running your api as Windows services can have multiple advantages, especially when working on bigger projects. This allows for multiple (services to run in isolation and gives fine grained control over your system components. ASP.NET Web API ships wi

(WCF) WCF Service Hosting.

3 Options. 1. Host inside of an application. 2. Host into Windows service. 3. Host into IIS 参考: http://www.codeproject.com/Articles/38160/WCF-Service-Library-with-Windows-Service-Hosting http://www.tuicool.com/articles/URBfm2

(WCF) WCF and Service Debug

需要做一个多程序间的通讯,采用WCF和WCF Service是目前的选择. 需求:和产品进行通讯,和用户有交互操作,并将最后结果传送个DB 基本思路: 1. 用WPF客户端程序和产品进行通讯,获取必要的结果. 2. WPF客户端程序里调用WCF 的Proxy, 将结果传送个WCF Service. 3. 另外一个程序通过另一个WCF Proxy获取结果,并传送到DB Control System(Service)             <-------------------->   WCF

.Net Remoting的双向通信和Windows Service的宿主服务

原文:.Net Remoting的双向通信和Windows Service的宿主服务 作为微软分布式技术之一的.Net Remoting,从性能.安全等各方面来说都是相对比较稳定的,也是一项比较成熟的分布式技术. 从学习.Net Remoting至今,仅仅只使用了一次这门技术,是在去年的一个IM产品中.最近公司的产品出现了很多问题,服务器.通信接口.网站都陆续被攻击(DDOS).这对于做互联网产业的同行来说就清楚这里面的关系,强大的DDOS攻击可以直接让产品无法正常运营甚至停止运营. 经过一系列

Windows service wrapper 初探

Windows 服务包装器(Windows service wrapper),用于把.exe文件注册为windows服务.比如把Nginx.exe注册为windows服务,这样做的好处是,每次启动nginx时不用在命令行中输入命令,而且可以随windows系统启动而启动.不用担心服务器意外重启,服务挂掉. github地址:https://github.com/kohsuke/winsw 下载地址:https://github.com/kohsuke/winsw/releases 目前(2017

C# Windows Service中执行死循环轮询

用C#编写Windows Service时,执行轮询一般有两种方式,一种是用Timer,System.Timers或者是System.Thread下的,这种执行是按时间循环执行,缺点是也许上个执行还没有完成,又开始执行新的. 另一种方式是利用线程,在OnStart里单开一个线程去跑含有死循环结构的函数,这种方式的缺点是,对线程的控制困难,停止服务了,线程还有可能在执行,不过 .Net 4.0+ 给我们提供了 CancellationTokenSource,用来取消正在运行的线程(Task),代码