WCF宿主Window Service Demo

尝试了下将服务寄宿在window 服务上。具体步骤如下

整个解决方案截图

一、创建window 服务

     Wcf.WinService

     

namespace Wcf.WinService
{
    public partial class CalService : ServiceBase
    {
        public ServiceHost serviceHost = null; //服务宿主

        public CalService()
        {
            InitializeComponent();
            base.ServiceName = "WCF.ServiceHostByWindowService";
        }

        protected override void OnStart(string[] args)
        {
           
            if(serviceHost != null)
            {
                serviceHost.Close();
            }
            serviceHost = new ServiceHost(typeof(Cal));
            serviceHost.Open();          
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
            base.OnStop();
        }
    }
}
window 服务代码

 

 二、创建数据契约,wcf服务类

       

namespace Wcf.WinService
{
    [ServiceContract]
    public interface ICal
    {

        [OperationContract]
        int Add(int a, int b);

         [OperationContract]
        string GetValue(string value);

    }
}
服务契约
namespace Wcf.WinService
{
    public class Cal : ICal
    {

        public int Add(int a, int b)
        {
            return a+b;
        }

        public string GetValue(string value)
        {
            return "hello " + value;
        }
    }
}
Cal服务

 

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
  <services>
    <service name="Wcf.WinService.Cal"  behaviorConfiguration="basicBehavior">
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:8999/CalService"/>
        </baseAddresses>
      </host>
      <endpoint address="http://localhost:8999/CalServices" 
                contract="Wcf.WinService.ICal" 
                binding="basicHttpBinding" />
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="basicBehavior">
        <serviceMetadata httpGetEnabled="true" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
</configuration>
wcf服务端配置

 

三、安装window服务

    1.双击CalService,右键增加安装程序,项目中会自动增加一个ProjectInstaller的文件,且该上面包含serviceProcessInstaller1 和serviceInstaller1 两个组件

    2. 设置serviceProcessInstaller1的属性Account为LocalSystem ,设置serviceInstaller1的ServiceName:WCF.CalService(最终服务的名字,可自己随便设置)

    3.生成解决方案,讲debug下 Wcf.WinService.exe 和 Wcf.WinService.exe.config 复制到D盘

    4.以管理员方式运行vs2012开发人员命令提示,安装服务 installUtil D:\Wcf.WinService.exe,到此服务安装成功,去服务管理把服务开启

   5.卸载服务  InstallUtil.exe -u D:\Wcf.WinService.exe

 

四、Client段调用

    客户端引用服务地址 http://localhost:8999/CalService,引用后,客户端配置文件自动生成。

在客户端验证既可以。

整个解决方案源代码下载

posted @ 2014-09-10 11:39  lance2008  阅读(695)  评论(0编辑  收藏  举报