我对WCF很新。你如何在WinForm中托管WCF服务?显然,该服务只有在表格打开时才可用,但这正是我所追求的。
我发现只有少数(差)这样做的例子,甚至MSDN开始讨论在WinForm中托管一个但是然后在Windows服务中实现它。
答案 0 :(得分:1)
您可以打开自己的应用,并在表单中放置以下内容:
创建您的WCF界面
<ServiceContract()>
Public Interface IyourInterface
<OperationContract()>
Function asyouwant ....
创建实现它的类
Public Class clsYourClass
Implements IyourInterface
从winforms app中实例化。
(这是vb.net)
Dim oYourService As ServiceHost
Dim oYourBinding As New System.ServiceModel.BasicHttpBinding
' Or WSHttpBinding ... configure as you want
Dim aAddress As Uri()
aAddress= New Uri() {New Uri("http://localhost:port")}
oYourService = New ServiceHost(GetType(clsYourClass), aAddress)
oYourService.AddServiceEndpoint(GetType(IyourInterface), oYourBinding, "myWinformService.svc")
oYourService.Open()
答案 1 :(得分:-1)
简单的服务,例如..
<强> IService 强>
[ServiceContract]
public interface IService
{
[OperationContract]
string Calculate(int price, int Qty);
}
服务
public class Service : IService
{
public string Calculate(int price, int Qty)
{
return Convert.ToString(price * Qty);
}
}
按用户使用服务
转到添加服务引用选项并发现服务。添加服务。现在该服务显示在解决方案资源管理器中。
http://localhost/WCFServiceSample/Service.svc
检入网络浏览器。
应用程序中的用法
using WindowsFormsApplicationWCF.ServiceReference1;
Service1Client obj = new Service1Client();
private void btnSubmit_Click(object sender, EventArgs e)
{
string result;
result = obj.Calculate(Convert.ToInt32(txtPrice.Text), Convert.ToInt32(txtQty.Text));
lblresult.Text = "The total price is" + result;
}
请查看这些链接以供参考,
Hosting WCF service inside a Windows Forms application
http://www.c-sharpcorner.com/UploadFile/0c1bb2/consuming-wcf-service-in-windows-application/
https://msdn.microsoft.com/en-us/library/ms731758(v=vs.110).aspx