WCF使用windows服务作为宿主

Posted 零七八碎的资料

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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服务作为宿主的主要内容,如果未能解决你的问题,请参考以下文章

windows服务或winform来做WCF服务宿主的问题

如何通过wcf服务更新宿主项目中的winform控件?

如何通过wcf服务更新宿主项目中的winform控件?

WCF寄宿(Host)之自我寄宿(Self-Hosting)简单实例Windows应用程序宿主

使用IIS发布WCF服务

创建一个简单的WCF程序