设为首页 收藏本站
查看: 775|回复: 0

[经验分享] 化零为整WCF(5)

[复制链接]

尚未签到

发表于 2015-8-12 11:07:12 | 显示全部楼层 |阅读模式
[索引页]
[源码下载]



化零为整WCF(5) - 宿主Hosting(宿主在IIS, Application, WAS, WindowsService)

作者:webabcd


介绍
WCF(Windows Communication Foundation) - 宿主(Hosting):WCF服务可以宿主在IIS, Application, WAS, WindowsService。本文以宿主在WindowsService为例。


示例
1、服务
IHello.cs

DSC0000.gif using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;

namespace WCF.ServiceLib.Sample
DSC0001.gif DSC0002.gif DSC0003.gif {
DSC0004.gif DSC0005.gif     /**//// <summary>
DSC0006.gif     /// IHello接口
DSC0007.gif     /// </summary>
    [ServiceContract]
    public interface IHello
    {
        /**//// <summary>
        /// 打招呼方法
        /// </summary>
        /// <param name="name">人名</param>
        /// <returns></returns>
        [OperationContract]
        string SayHello(string name);
    }
DSC0008.gif }

Hello.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;

namespace WCF.ServiceLib.Sample
{
    /**//// <summary>
    /// Hello类
    /// </summary>
    public class Hello : IHello
    {
        /**//// <summary>
        /// 打招呼方法
        /// </summary>
        /// <param name="name">人名</param>
        /// <returns></returns>
        public string SayHello(string name)
        {
            return "Hello: " + name;
        }
    }
}


2、宿主
Hello.cs(WindowsService)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ComponentModel;
using System.Configuration;
using System.Configuration.Install;
using System.ServiceModel;
using System.ServiceProcess;

namespace WCF.ServiceHostByWindowsService.Sample
{
    /**//// <summary>
    /// 初始化 System.Configuration.Install.Installer 类的新实例。
    /// </summary>
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        /**//// <summary>
        /// 构造函数
        /// </summary>
        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "WCF.ServiceHostByWindowsService";
            service.Description = "WCF服务宿主在WindowsService[webabcd测试用]";
            base.Installers.Add(process);
            base.Installers.Add(service);
        }
    }

    /**//// <summary>
    /// Windows服务类
    /// </summary>
    public class WindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;

        /**//// <summary>
        /// 主函数
        /// </summary>
        public static void Main()
        {
            ServiceBase.Run(new WindowsService());
        }

        /**//// <summary>
        /// 构造函数
        /// </summary>
        public WindowsService()
        {
            base.ServiceName = "WCF.ServiceHostByWindowsService";
        }

        /**//// <summary>
        /// 启动Windows服务
        /// </summary>
        /// <param name="args">args</param>
        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            // 为WCF.ServiceLib.Sample.Hello创建ServiceHost
            serviceHost = new ServiceHost(typeof(WCF.ServiceLib.Sample.Hello));

            serviceHost.Open();

            ServiceHost的几个事件(顾名思义)#region ServiceHost的几个事件(顾名思义)
            /**//*
            serviceHost.Opening +=
            serviceHost.Opened +=
            serviceHost.Closing +=
            serviceHost.Faulted +=
            serviceHost.UnknownMessageReceived +=
             */
            #endregion
        }

        /**//// <summary>
        /// 停止Windows服务
        /// </summary>
        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <!--name - 提供服务的类名-->
      <!--behaviorConfiguration - 指定相关的行为配置-->
      <service name="WCF.ServiceLib.Sample.Hello" behaviorConfiguration="SampleBehavior">
        <!--address - 服务地址-->
        <!--binding - 通信方式-->
        <!--contract - 服务契约-->
        <endpoint address="" binding="wsHttpBinding" contract="WCF.ServiceLib.Sample.IHello" />
        <!--元数据交换的endpoint-->
        <!--注:address是mex,它会和host/baseAddresses节点中的baseAddress做拼接,即提供元数据交换的地址为:http://localhost:12345/Binding/mex-->
        <endpoint binding="mexHttpBinding" contract="IMetadataExchange" address="mex" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:11233/ServiceHostByWindowsService/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="SampleBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>


3、客户端
Hello.aspx

<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Hello.aspx.cs"
    Inherits="Hosting_Hello" Title="宿主Hosting(服务宿主在WindowsService)" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div>
        <ul>
            <li style="color: Red;">本例为宿主在WindowsService的示例</li>
            <li>宿主在IIS请参见本解决方案的ServiceHost项目</li>
            <li>宿主在应用程序请参见本解决方案的ServiceHost2项目</li>
            <li>应用程序自宿主就是把本解决方案的ServiceLib项目和ServiceHost2项目结合在一起</li>
            <li>宿主在Windows Activation Services(WAS),因为我没有环境,就先不写示例了</li>
        </ul>
    </div>
    <asp:TextBox ID="txtName" runat="server" Text="webabcd" />
    &nbsp;
    <asp:Button ID="btnSayHello" runat="server" Text="Hello" OnClick="btnSayHello_Click" />
</asp:Content>

Hello.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Hosting_Hello : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSayHello_Click(object sender, EventArgs e)
    {
        var proxy = new HostingByWindowsService.HelloClient();

        Page.ClientScript.RegisterStartupScript(
            this.GetType(),
            "js",
            string.Format("alert('{0}')", proxy.SayHello(txtName.Text)),
            true);

        proxy.Close();
    }
}

Web.config

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <client>
      <!--address - 服务地址-->
      <!--binding - 通信方式-->
      <!--contract - 服务契约-->
      <endpoint address="http://localhost:11233/ServiceHostByWindowsService/" binding="wsHttpBinding" contract="Sample.IHello" />
    </client>
  </system.serviceModel>
</configuration>


运行结果:
启动"WCF.ServiceHostByWindowsService"服务,单击"Hello"按钮后弹出提示框,显示"Hello: webabcd"


OK
[源码下载]

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-97858-1-1.html 上篇帖子: 一步步教你创建.NET 4服务并且寄宿在IIS 7.5中 下篇帖子: 满园尽是503,记曾经的一次IIS 7性能考验
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表