【问题标题】:Hosting a WCF Service In A WinForm [duplicate]在 WinForm 中托管 WCF 服务 [重复]
【发布时间】:2015-07-07 08:57:35
【问题描述】:

我对 WCF 很陌生。如何在 WinForm 中托管 WCF 服务?显然,该服务仅在表单打开时可用,但这正是我所追求的。

我发现只有几个(糟糕的)例子,甚至 MSDN 也开始谈论在 WinForm 中托管一个,然后在 Windows 服务中实现它。

【问题讨论】:

标签: c# winforms wcf


【解决方案1】:

您可以打开您的应用,然后在表单中放置类似这样的内容:

  1. 创建您的 WCF 界面

    <ServiceContract()>
    Public Interface IyourInterface
    <OperationContract()>
    Function asyouwant ....
    
  2. 创建实现它的类

    Public Class clsYourClass
    Implements IyourInterface
    
  3. 从您的 winforms 应用程序中实例化它。

    (这是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()
    

4 - 试试这个:http://localhost:port/myWinformService.svc

【讨论】:

    【解决方案2】:

    例如简单的服务..

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多