WCF使用windows服务作为宿主

ICalculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace WindowsService1
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
    }
}
CalculatorService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace WindowsService1
{
    // Implement the ICalculator service contract in a service class.  (InstanceContextMode=InstanceContextMode.Single)
    [ServiceBehavior]
    public class CalculatorService : WindowsService1.ICalculator
    {
        // Implement the ICalculator methods.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            return result;
        }
    }
}
CalculatorWindowsService.cs
using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.IO;

namespace WindowsService1
{
    public partial class CalculatorWindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;

        public CalculatorWindowsService()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            if(serviceHost != null){
                serviceHost.Close();
            }
            serviceHost = new ServiceHost(typeof(CalculatorService));
            serviceHost.Open();
        }
        protected override void OnStop()
        {
            if(serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="basicBehavior" name="WindowsService1.CalculatorService">

        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WindowsService1.ICalculator" />
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://127.0.0.1:9999/CalculatorService" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="basicBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:9998/CalculatorService/metadata"
            httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

可以去除App.config,使用代码直接配置

protected override void OnStart(string[] args)
{
    if(serviceHost != null){
        serviceHost.Close();
    }
    try
    {
        serviceHost = new ServiceHost(typeof(WindowsService1.CalculatorService)
             ,new Uri("http://127.0.0.1:9999/CalculatorService") );

        ServiceMetadataBehavior smb = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
        if (smb == null){
            smb = new ServiceMetadataBehavior();
        }
        smb.HttpGetEnabled = true;
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        serviceHost.Description.Behaviors.Add(smb);

        serviceHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName,
            MetadataExchangeBindings.CreateMexHttpBinding(),
            "mex");
        serviceHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "");

        serviceHost.Open();
    }
    catch (Exception ex)
    {

    }
}

1.测试工具使用wcftestclient

2.客户端测试:

using System;
using System.ServiceModel;
using WindowsService1;

namespace TestWindowsServiceClient
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
            //http
            ICalculator client = ChannelFactory<ICalculator>.CreateChannel(
                new WSHttpBinding(),
                new EndpointAddress("http://127.0.0.1:9999/CalculatorService"));
            */

            //tcp
            ICalculator client = ChannelFactory<ICalculator>.CreateChannel(
                new NetTcpBinding(),
                new EndpointAddress("net.tcp://127.0.0.1:9999/CalculatorService"));

            double ret = client.Add(23.0, 2.0);
            Console.WriteLine("Add result: {0}", ret);

            Console.Read();
        }
    }
}
时间: 2024-08-28 13:15:08

WCF使用windows服务作为宿主的相关文章

C#判断程序是由Windows服务启动还是用户启动

在Windows系统做网络开发,很多时候都是使用Windows服务的模式,但在调度阶段,我们更多的是使用控制台的模式.在开发程序的时候,我们在Program的Main入口进行判断.最初开始使用Environment.UserInteractive属性,在系统不系统服务的交互模式时,程序运行是正常的,但试过有Win7下,系统允许交互模式,结果在服务启动的时候,跳转到控制台的模式了,服务启动不起来.只能在服务的调用方式下带参数,然后在Main的参数中判断是否为服务方式.这在一般的情况下是可以解决问题

使用C#创建及调用WCF完整实例 (Windows服务宿主)

关于WCF的概念.原理.优缺点等,在这里就不多说了,网上很多,可以自行搜索,比我解释的要专业的多. 这里直接说使用Windows 服务(Windows Service)作为宿主如何实现,其它方式不在此次教程之内 文章最后有本例的下载连接,包含源代码.说明教程.编译后文件 实例环境:Windows Server 2008 R2 + VS 2010(C#) 打开 VS 2010,选择 新建项目,选择 ”WCF”|”WCF 服务库 ”,注意这里是”WCF 服务库 ”,不是"WCF 服务应用程序&quo

wcf Rest 服务宿主在windows服务及客户端访问

首先写好服务,代码如下: 1 using System; 2 using System.Collections.Generic; 3 using System.Runtime.Serialization; 4 using System.ServiceModel.Web; 5 using System.ServiceModel; 6 7 8 namespace Artech.WcfServices.Service 9 { 10 [ServiceContract(Namespace = "Artec

将WCF寄宿在托管的Windows服务中

在我之前的一篇博客中我介绍了如何发布WCF服务并将该服务寄宿于IIS上,今天我再来介绍一种方式,就是将WCF服务寄宿在Windows服务中,这样做有什么好处呢?当然可以省去部署IIS等一系列的问题,能够让部署更加简单,当然WCF的寄宿方式一般分为以下四种方式,针对每一种方式我来简单介绍以下: 具体的寄宿方式详细信息请参考MSDN:https://msdn.microsoft.com/zh-cn/library/ms733109(v=vs.100).aspx 一.WCF服务寄宿方式: 1):寄宿在

WCF服务寄宿IIS与Windows服务

WCF是Windows平台下程序间通讯的应用程序框架.整合和 .net Remoting,WebService,Socket的机制,是用来开发windows平台上分布式开发的最佳选择.wcf程序的运行需要一个宿主ServiceHost,我们可以选用控制台应用程序,也可以选择IIS寄宿,还可以选择windows 服务寄宿.相较与控制台程序,IIS,和Windows服务比较稳定.而且大家不会时不时的去重启下IIS下的网站,或者windows服务. 在IIS下寄宿Wcf 我们新建一个类库项目 在项目下

微软 WCF的几种寄宿方式,寄宿IIS、寄宿winform、寄宿控制台、寄宿Windows服务

WCF寄宿方式是一种非常灵活的操作,可以在IIS服务.Windows服务.Winform程序.控制台程序中进行寄宿,从而实现WCF服务的运行,为调用者方便.高效提供服务调用.本文分别对这几种方式进行详细介绍并开发例子进行说明,以求大家对WCF寄宿的方式进行全面的认识和了解. 1. WCF服务的IIS服务寄宿 我在我前面几篇WCF开发框架的介绍文章中,介绍过了WCF常用的一种寄宿方式,IIS服务寄宿.这种寄宿方式是最为方便的方式,而且由于服务只需要IIS运行就能自动运行起来,因此广为使用. 创建这

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

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

.NET Framework 4.6 and 4.5 &gt; 开发指南 &gt; 使用 WCF 的面向服务的应用程序 &gt; Windows Communication Foundation (WCF)

.NET Framework 4.6 and 4.5 > 开发指南 >  使用 WCF 的面向服务的应用程序 > Windows Communication Foundation (WCF) :https://msdn.microsoft.com/zh-cn/library/dd456779(v=vs.110).aspx 文档指南: https://msdn.microsoft.com/zh-cn/library/ms730846(v=vs.110).aspx 入门教程: https:/

Windows服务承载WCF

Source文件 ------------------------- 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 using System.ComponentModel; 7 using System.ServiceModel; 8 using System.ServiceProcess; 9 using System.Configuration