-1

I am quite new to WCF. How do you host a WCF service in a WinForm? Obviously the service would only be available while the form is open but this is exactly what I am after.

There are only a few (poor) examples of doing it which I have found and even the MSDN starts talking about hosting one in a WinForm but then goes and implements it in a Windows Service.

TimR75
  • 379
  • 2
  • 13

2 Answers2

1

You can open your app, and place something like this in your form:

  1. Create your WCF interface

    <ServiceContract()>
    Public Interface IyourInterface
    <OperationContract()>
    Function asyouwant ....
    
  2. Create the class that implements it

    Public Class clsYourClass
    Implements IyourInterface
    
  3. Instantiate it from your winforms app.

    (This is 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 - Try this: http://localhost:port/myWinformService.svc

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Morcilla de Arroz
  • 2,104
  • 22
  • 29
-1

Simple service for example..

IService

[ServiceContract]
public interface IService
{
    [OperationContract]
    string Calculate(int price, int Qty);
}

Service

public class Service : IService
    {
        public string Calculate(int price, int Qty)
        {
            return Convert.ToString(price * Qty);
        }
    } 

Consume service by user

Go to Add Service reference option and discover the service. Add the service. Now the service displays in solution explorer.

http://localhost/WCFServiceSample/Service.svc

To check in web browser.

Usage in Application

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;
    }

Check these links for you reference,

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

Community
  • 1
  • 1
kasim
  • 346
  • 2
  • 5
  • 23