wcf自身作为宿主的一个小案例

第一步:创建整个解决方案  

service.interface:用于定义服务的契约(所有的类的接口)引用了wcf的核心程序集system.ServiceModel.dll

service:用于定义服务类型的类库项目(所有的类)实现了service.interface的所有接口

hosting:控制台应用程序 同时引用了上面的两个程序集

Client:模拟服务的客户端

第二部:在service.interface中定义接口及方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Server.Interface
{
    [ServiceContract(Name = "UserServer",  Namespace = "http://www.LiuText.com")]
    public interface IUser
    {
        [OperationContract]
        string GetName(string name);
    }
}

第三部:实现接口并编写方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Server.Interface;
namespace Server
{
    public class User:IUser
    {
        public string GetName(string name)
        {
            return "我的名字是" + name;
        }
    }
}

第四部:编写应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using Server;
using Server.Interface;
namespace Hosting
{
    public class Program
    {
        public static void main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(IUser)))
            {
                host.AddServiceEndpoint(typeof(IUser), new WSHttpBinding(), "http://172.168.0.1/UserServer");
                if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
                {
                    ServiceMetadataBehavior beh = new ServiceMetadataBehavior();
                    beh.HttpGetEnabled = true;
                    beh.HttpGetUrl = new Uri("http://172.168.0.1/UserServer/metadata");
                    host.Description.Behaviors.Add(beh);
                }
                host.Opened += delegate
                {
                    Console.WriteLine("服务启动!!");
                };
                host.Open();
                Console.ReadLine();
            }
        }
    }
}

第五步:运行程序并访问程序中所写的路径

这样一个wcf就配好了   就可以调用了

posted @ 2014-04-21 17:19  流浪的狸猫  阅读(216)  评论(0编辑  收藏  举报