WCF使用纯代码的方式进行服务寄宿

服务寄宿的目的是为了开启一个进程,为WCF服务提供一个运行的环境。通过为服务添加一个或者多个终结点,使之暴露给潜在的服务消费,服务消费者通过匹配的终结点对该服务进行调用,除去上面的两种寄宿方式,还可以以纯代码的方式实现服务的寄宿工作。

新建立一个控制台应用程序,添加System.ServiceModel库文件的引用。

添加WCF服务接口:ISchool使用ServiceContract进行接口约束,OperationContract进行行为约束

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


namespace WcfTest.Demo3
{
    [ServiceContract]
    public interface ISchool
    {
        [OperationContract]
        string ShowName(string Name);
    }
}

添加School类,实现Ishool接口:

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

namespace WcfTest.Demo3
{
    public class School:ISchool
    {
        public string ShowName(string name)
        {
            return "Show Name " + name;
        }
    }
}

通过代码将ISchool接口寄宿到控制台应用程序之中。

    class Program
    {
        static void Main(string[] args)
        {
            CoreCodeOpen();
        }

        /// <summary>
        /// 通过代码的方式完成服务的寄宿工作
        /// </summary>
        static void CoreCodeOpen()
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(School)))
                {
                    host.AddServiceEndpoint(typeof(ISchool), new WSHttpBinding(), "http://10.0.0.217:20004/School");
                    if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                    {
                        ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                        behavior.HttpGetEnabled = true;
                        behavior.HttpGetUrl = new Uri("http://10.0.0.217:20004/School/wcfapi");
                        host.Description.Behaviors.Add(behavior);
                    }
                    host.Open();
                    Console.WriteLine("寄宿到控制台应用程序,通过代码开启WCF服务");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("CoreCodeOpen Error:" + ex.Message);
            }
        }
    }

以管理员身份运行程序>在浏览器输入http://10.0.0.217:20004/School/wcfapi>我们会得到以WSDL(网络服务描述语言-Web Services Description Language)形式体现的服务元数据

在解决方案中新建控制台客户端,添加服务引用,输入http://10.0.0.217:20004/School/wcfapi

找到了我们的Ischool服务接口,添加引用后进行服务的调用。

posted @ 2018-03-07 10:58  小何同學  阅读(771)  评论(0编辑  收藏  举报