参考地址:http://www.cnblogs.com/zhili/p/4039111.html

一、如何在Windows Services中寄宿WCF服务

  • 第一步:创建Windows 服务项目,具体添加步骤为右键解决方案->添加->新建项目,在已安装模板中选择Windows 服务模板,具体如下图示所示:
  • 第二步:添加Windows服务之后,修改对应的Service1.cs文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Service; namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
} private ServiceHost serviceHost;
/// <summary>
/// 启动Windows服务
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(Service.CalculatorService));
//可以使用代码
//serviceHost.AddServiceEndpoint(typeof(ICalculatorService), new WSHttpBinding(),
// "http://127.0.0.1:3721/calculatorservice");
//if (serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
//{ // ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
// behavior.HttpGetEnabled = true;
// behavior.HttpGetUrl = new Uri("http://127.0.0.1:3721/calculatorservice/metadata");//通过该地址获取服务相关的元数据
// serviceHost.Description.Behaviors.Add(behavior);
//}
serviceHost.Open();
} /// <summary>
/// 停止Windows服务
/// </summary>
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks; namespace Service
{
[ServiceContract(Name = "CalculatorService1",//服务契约的名称,也就是客户端调用者生成代理类的接口名称
Namespace = "http://www.yxl.com")]//服务契约命名空间
public interface ICalculatorService
{
[OperationContract]
double Add(double x, double y);
}
public class CalculatorService : ICalculatorService
{
public double Add(double x, double y)
{
return x + y;
}
} }
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:3721/calculatorservice/metadata"/><!--调用地址-->
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="Service.CalculatorService" behaviorConfiguration="metadataBehavior">
<endpoint address="http://127.0.0.1:3721/calculatorservice" binding="wsHttpBinding" contract="Service.ICalculatorService" />
</service>
</services>
</system.serviceModel>
</configuration>
  • 第三步:在WindowsService的设计界面,右键选择添加安装程序,具体操作如下图所示。

  添加安装程序之后,会多出一个ProjectInstaller.cs文件,然后在其设计页面修改ServiceProcessInstallerServiceInstaller对象属性,具体设置的值如下图所示:

  经过上面的步骤,程序的代码就都已经全部实现了,接下来要做的是安装Windows 服务和启动Windows服务。

  首先是安装Windows服务:以管理员身份运行VS2012开发命令提示,进入项目的对应的exe所在的文件夹,这里的指的是WindowsServiceHost.exe所在的文件夹,然后运行 “installutil WindowsServiceHost.exe”命令,命令运行成功后,你将看到如下所示的运行结果:

  安装成功之后,你可以运行 “net start HelloWorldServiceHost” 命令来启动服务。因为开始设置服务的名称是HelloWorldServiceHost。你也可以通过Services中来手动启动服务,启动成功之后,你将在服务窗口看到启动的服务。具体效果如下图所示。

  服务启动后,在客户端中同样是添加服务引用的方式来添加服务引用

二、使用WindowsService作为宿主的好处:

  1. windows服务可以在系统后台长时间运行,由操作系统控制。
  2. windows服务可以通过管理器方便的暂停、停止、启动,方便管理程序。
  3. 最重要的一点就是windows服务是我们开发中常用到的,我们不可能运行一个控制台程序一直在服务器运行,因为不知道哪个人就会关闭掉,安全性较差。
  4. 简单的运行wcf服务在windows服务中还看不出来复杂性,随着项目的复杂,配置项也是方便管理的,因为可以停止、重新启动。

三、解决WCF操作契约重载问题

C#语言是支持操作重载的,然而在WCF实现操作重载有一定的限制。错误的操作重载实例:

[ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")]
public interface IHelloWorld
{
[OperationContract]
string GetHelloWorld(); [OperationContract]
string GetHelloWorld(string name);
}

如果你像上面一样来实现操作重载的话,在开启服务的时候,你将收到如下图所示的异常信息:

  然而,为什么WCF不允许定义两个相同的操作名称呢?原因很简单,因为WCF的实现是基于XML的,它是通过WSDL来进行描述,而WSDL也是一段XML。在WSDL中,WCF的一个方法对应一个操作(operation)标签。我们可以参考下面一段XML,它是从一个WCF的WSDL中截取下来的。

<wsdl:import namespace="http://www.Learninghard.com" location="http://localhost:9999/GetHelloWorldService?wsdl=wsdl0"/>
<wsdl:types/>
<wsdl:binding name="BasicHttpBinding_HellworldService" type="i0:HellworldService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="GetHelloWorldWithoutParam">
<soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithoutParam" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="GetHelloWorldWithParam">
<soap:operation soapAction="http://www.Learninghard.com/HellworldService/GetHelloWorldWithParam" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="HelloWorldService">
<wsdl:port name="BasicHttpBinding_HellworldService" binding="tns:BasicHttpBinding_HellworldService">
<soap:address location="http://localhost:9999/GetHelloWorldService"/>
</wsdl:port>
</wsdl:service>

从上面的代码可以看出,每个Operation由一个operation XML Element表示,而每个Operation还应该具有一个能够唯一表示该Operation的ID,这个ID则是通过name属性来定义。Operation元素的Name属性通常使用方法名来定义,所以,如果WCF服务契约中,包含两个相同的操作方法名时,此时就违背了WSDL的规定,这也是WCF不可以使用操作重载的原因。

如何解决呢?

指定操作契约名称:

namespace Contract
{
[ServiceContract(Name = "HellworldService", Namespace = "http://www.Learninghard.com")]
public interface IHelloWorld
{
[OperationContract(Name = "GetHelloWorldWithoutParam")]
string GetHelloWorld(); [OperationContract(Name = "GetHelloWorldWithParam")]
string GetHelloWorld(string name);
}
}

这种方式在客户端生成的代理类的方法名分别为GetHelloWorldWithoutParam和GetHelloWorldWithParam,看不出来是重载方法,可以自己实现客户端代理类,而不是由VS代码生成工具。具体重新的proxy Class的实现代码代码如下所示:

using Contract;
using System.ServiceModel;
namespace Client2
{
class HellworldServiceClient : ClientBase<IHelloWorld>, IHelloWorld
{
#region IHelloWorld Members
public string GetHelloWorld()
{
return this.Channel.GetHelloWorld();
} public string GetHelloWorld(string name)
{
return this.Channel.GetHelloWorld(name);
}
#endregion
}
}

此时客户端的实现代码和配置文件如下所示:

namespace Client2
{
class Program
{
static void Main(string[] args)
{
using (var proxy = new HellworldServiceClient())
{
// 通过自定义代理类来调用进行服务方法的访问
Console.WriteLine("服务返回的结果是: {0}", proxy.GetHelloWorld());
Console.WriteLine("服务返回的结果是: {0}", proxy.GetHelloWorld("Learning Hard"));
} Console.Read();
}
}
}

对应的配置文件如下所示:

<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:9999/GetHelloWorldService"
binding ="basicHttpBinding"
contract ="Contract.IHelloWorld"/>
</client>
</system.serviceModel>
</configuration>

重温WCF之构建一个简单的WCF(一)(2)通过Windows Service寄宿服务和WCF中实现操作重载的更多相关文章

  1. WCF学习——构建一个简单的WCF应用(一)

    本文的WCF服务应用功能很简单,却涵盖了一个完整WCF应用的基本结构.希望本文能对那些准备开始学习WCF的初学者提供一些帮助. 在这个例子中,我们将实现一个简单的计算器和传统的分布式通信框架一样,WC ...

  2. 重温WCF之构建一个简单的WCF(一)(1)通过控制台和IIS寄宿服务

    一.理解什么是WCFWCF就是.NET平台下各种分布式技术的集成,并提供了一套统一的编程接口 二.WCF的定义WCF(Windows Communication Foundation)是微软为构建面向 ...

  3. WCF学习——构建一个简单的WCF应用(二)

    我们接着上一篇文章进行讲解 http://www.cnblogs.com/songjianhui/p/7060698.html 一:客户端通过添加引用调用服务 WCF应用服务被成功寄宿后,WCF服务应 ...

  4. struts1:(Struts重构)构建一个简单的基于MVC模式的JavaWeb

    在构建一个简单的基于MVC模式的JavaWeb 中,我们使用了JSP+Servlet+JavaBean构建了一个基于MVC模式的简单登录系统,但在其小结中已经指出,这种模式下的Controller 和 ...

  5. 【Android Developers Training】 3. 构建一个简单UI

    注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...

  6. 构建一个简单的Linux系统 MenuOs —— start_kernel到init进程(20135304刘世鹏)

    构建一个简单的Linux系统 MenuOs —— start_kernel到init进程 作者:刘世鹏20135304 <Linux内核分析>MOOC课程http://mooc.study ...

  7. gRPC初探——概念介绍以及如何构建一个简单的gRPC服务

    目录 引言 1. gRPC简介 2. 使用Protocol Buffers进行服务定义 2.1 定义消息 2.2 定义服务接口 3.构建简单的gRPC服务 3.1 编写proto文件,定义消息和接口 ...

  8. 第三周——构建一个简单的Linux系统MenuOS

    [洪韶武 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 ] 第三周  构建一个 ...

  9. 构建一个简单的基于MVC模式的JavaWeb

    零晨三点半了,刚刚几个兄弟一起出去吼歌,才回来,这应该是我大学第二次去K歌,第一次是大一吧,之后每次兄弟喊我,我都不想去,因为我还是很害怕去KTV,或许是因为那里是我伤心的地方,也或许是因为我在那里失 ...

随机推荐

  1. 跟着百度学PHP[4]OOP面对对象编程-11-Final关键字

    Final的作用就是不允许儿子继承夫类,也就是说不能够对父类在进行调用,否则将会出错. 目录------------------------------------------------------ ...

  2. Service

      一.什么是Service Service在后台运行,不与用户进行交互.在默认情况下,Service运行在应用程序进程的主线程中,如果需要在Service中处理一些网络连接等耗时的操作,那么应该将这 ...

  3. @ResponseBody返回不能正确接收

    Spring-MVC中@ResponseBody返回Bean到前台接收这么一串代码,还套着HTML标签: The resource identified by this request is only ...

  4. 【System】shell 实现 bat 的pause功能

    read -rsp $'Press enter to continue...\n' 参考资料: http://stackoverflow.com/questions/92802/what-is-the ...

  5. Expression表达式树

    表达式树表示树状数据结构的代码,树状结构中的每个节点都是一个表达式,例如一个方法调用或类似 x < y 的二元运算 1.利用 Lambda 表达式创建表达式树 Expression<Fun ...

  6. 【Unity3D】使用鼠标键盘控制Camera视角(即时战略类游戏视角):缩近,拉远,旋转

    今天写一个demo,要用到鼠标键盘控制三维视角,因此写了个脚本用于控制. 该脚本可以用于即时战略类游戏的视角,提供了缩进,拉伸,旋转.同时按住鼠标右键不放,移动鼠标可以实现第一人称视角的效果. usi ...

  7. Debian安装python-rrdtool

    ... sudo apt-get install rrdtool sudo apt-get install librrd-dev sudo apt-get install python-dev pip ...

  8. CEF3开发者系列之CEF3入门

    CEF全称Chromium Embedded Framework,是一个基于Google Chromium 的开源项目.Google Chromium项目主要是为Google Chrome应用开发的, ...

  9. iOS FMDB 不需要关闭

    以前做了一个应用,里面用到了FMDB,进行每一次操作前,都open,完成操作后都close.因为我是参考他们以前的代码.程序初期没发现什么问题,程序完成后,各种卡顿就出现了!即使我是放在新线程里操作的 ...

  10. java访问数据库的sql

    drop database if exists STOREDB;create database STOREDB;use STOREDB; create table CUSTOMERS ( ID big ...