WCF中通过配置文件来创建启动服务

来源:互联网 发布:数据段字节变量 编辑:程序博客网 时间:2024/05/21 19:43
//1.类库
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ServiceModel;namespace WCFServiceDemo{    [ServiceContract]    public interface IHelloService    {        [OperationContract]        DateTime getDateTime();    }}

 

 

2. Winform应用程序(宿主程序)

using System;using System.Collections.Generic;using System.Linq;using System.Text;using WCFServiceDemo;namespace WinformHello{    public class HelloService:WCFServiceDemo.IHelloService    {        public DateTime getDateTime()        {            return DateTime.Now;        }    }}

 

3.配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="WinformHello.HelloService" behaviorConfiguration="TestBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8001/Hello"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WCFServiceDemo.IHelloService"></endpoint>
     
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="TestBehavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
   
  </system.serviceModel>
</configuration>

 

 

4.启动服务

 public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        ServiceHost host = null;        private void button1_Click(object sender, EventArgs e)        {            host = new ServiceHost(typeof(WinformHello.HelloService));            host.Open();            label1.Text = "服务已启动";        }    }