首页 > 代码库 > WCF使用windows服务作为宿主

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();
        }
    }
}

 

WCF使用windows服务作为宿主