利用winform来承载WCF服务

一般而言,我们用控制台承载WCF服务只需这样写就行了:

//定义承载服务的类型和承载服务的基址
using (ServiceHost host = new ServiceHost(typeof(Service1), new Uri("http://localhost:8839/CalculatorService")))
{
//增加一个服务终结点
host.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "CalculatorService");

//使用元数据
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //使用HTTP/GET请求
behavior.HttpGetEnabled = true;
//定义元数据发布地址
behavior.HttpGetUrl = new Uri("http://localhost:8839/CalculatorService/Metadata");
//将元数据的定义添加到承载服务中
host.Description.Behaviors.Add(behavior);
// 启动服务
host.Open();
Console.WriteLine("CalculatorService服务运行中...\n");
Console.WriteLine("按任意键退出.");
Console.Read();
// 关闭服务
host.Close();
}

然而,如果在winform里面,如果那样写的话,服务是起不来的,研究了大半个晚上,终于悟出原来是Using惹的祸,这样写就行了:

 

 ServiceHost host;

private void btnclose_Click(object sender, EventArgs e)
{
host.Close();
}

private void btnbegin_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(Service1), new Uri("http://localhost:8839/CalculatorService"));
//增加一个服务终结点
host.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "CalculatorService");

//使用元数据
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //使用HTTP/GET请求
behavior.HttpGetEnabled = true;
//定义元数据发布地址
behavior.HttpGetUrl = new Uri("http://localhost:8839/CalculatorService/Metadata");
//将元数据的定义添加到承载服务中
host.Description.Behaviors.Add(behavior);
// 启动服务
host.Open();
}

这样点击开始菜单,服务就Run起来了。

posted on 2012-09-28 09:17  潴潴黠  阅读(506)  评论(0编辑  收藏  举报