WCF的幾種寄宿方式

一、 WCF服務的控制檯程序寄宿

namespace WcfService_HostConsole
{
    class Program
    {
        static void Main(string[] args)
        {            
            try
            {
                ServiceHost serviceHost = new ServiceHost(typeof(Service1));
                if (serviceHost.State != CommunicationState.Opened)
                {
                    serviceHost.Open();
                }

                Console.WriteLine("WCF 服務正在運行......");
                Console.WriteLine("輸入回車鍵 <ENTER> 退出WCF服務");
                Console.ReadLine();
                serviceHost.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

二、WCF服務的Winform程序寄宿

namespace WcfService_HostWinform
{
    public partial class FrmMain : Form
    {
        ServiceHost serviceHost = null;
        BackgroundWorker worker = null;

        public FrmMain()
        {
            InitializeComponent();

            worker = new BackgroundWorker();
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);

            if (!worker.IsBusy)
            {
                textBox1.Text = "正在啓動......";
                worker.RunWorkerAsync();
            }
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                serviceHost = new ServiceHost(typeof(Service1));
                if (serviceHost.State != CommunicationState.Opened)
                {
                    serviceHost.Open();
                }

                e.Result = "正常";
            }
            catch (Exception ex)
            {
                e.Result = ex.Message;
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                if (e.Result.ToString() == "正常")
                {
                    textBox1.Text = "服務正在進行偵聽......";
                }
                else
                {
                    textBox1.Text = string.Format("錯誤:{0}", e.Result);
                }
            }
        }
    }
}

 

三、 使WCF服務支持GET方式調用

namespace WcfServiceForWinform
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        void DoWork();

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);
    }
}
namespace WcfServiceForWinform
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        public void DoWork()
        {
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }
}
<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true"/>
  </system.web>

  <system.serviceModel>
    <services>
      <service name="WcfServiceForWinform.Service1"  behaviorConfiguration="ServiceConfig">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" behaviorConfiguration="webHttpBehavior"
                  contract="WcfServiceForWinform.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9000/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>

    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"  />
      </webHttpBinding>
    </bindings>
    
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      
      <serviceBehaviors>
        <behavior name="ServiceConfig">
          <serviceMetadata httpGetEnabled="True" policyVersion="Policy15"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>
相關文章
相關標籤/搜索