WCF Self Hosting

12:15

Introduction

In this atricles I want to show how to implement self hosting in WCF.

What is Self Hosting?

Self Hosted is that it hosts the service in an application that could be a Console Application or Windows Forms and so on.

Why Self Hosting?

If want to host service of any application like Console application, Windows form etc. Than we use self hosting.
At first we create a service application and after that we use this service in a console application.

Create Service Application

Go to Visual studio > File > New > Project > Visual C# > Console Application
Provide the name of the application (Ex: WCfSelfHostingService) then click Ok


Right click on the project and add an interface. Like the following image:




After this we add a reference System.ServiceModel like below image:


Now we need to add an interface ICalculatorService.cs
In this interface we add a add service.
Interface ICalculatorService.cs code is below:
   
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace WCfSelfHostingService
{
    [ServiceContract()]
    public interface ICalculatorService
    {
        [OperationContract()]
        int Add(int a, int b);
    }
}
Now add a class CalculatorService.cs and implement add service like below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WCfSelfHostingService
{
    class CalculatorService : ICalculatorService
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}
We create a service End Point in the app.config file like below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
      <services>
        <service name="WCfSelfHostingService.CalculatorService" behaviorConfiguration="myMathServiceBehave">
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:8007/WCfSelfHostingService/" />
            </baseAddresses>
          </host>
          <endpoint address="http://localhost:8007/WCfSelfHostingService/CalculatorService" binding="basicHttpBinding" contract="WCfSelfHostingService.ICalculatorService"/>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="myMathServiceBehave">
            <serviceMetadata httpGetEnabled="true"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
</configuration>
Open Program.cs and add namespace System.ServiceModel
Program.cs code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace WCfSelfHostingService
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost svcHost = null;
            try
            {
                svcHost = new ServiceHost(typeof(WCfSelfHostingService.CalculatorService));
                svcHost.Open(); 
                Console.WriteLine("\n\nService is Running");
            }
            catch (Exception eX)
            {
                svcHost = null;
                Console.WriteLine("Service can not be started \n\nError Message [" + eX.Message + "]");
            } 
            
            if (svcHost != null)
            {
                Console.WriteLine("\nPress any key to close the Service");
                Console.ReadLine();
                svcHost.Close();
                svcHost = null;
            } 
        }
    }
}
Now run the service application we can see like below image:


Wow.. what is this? Our service showing an error!!!!!
If we show this error we need to close application first then go to all programs and Right click on the visual studio and click Run as administrator
Run application again we can see like below:


Now our service is ready and use this service to a console application.

Create A Client Application

Go to Visual studio > File > New > Project > Visual C# > Console Application
Provide the name of the application (Ex: WCfSelfHostingClient) then click Ok


Now right click on the References and click Add Reference... like below:


Now under Framework select Microsoft.CSharp Click Ok


We need to add the service reference.
Right click on the References and click Add Reference... Click Browse... button


Locate our service application WCfSelfHostingService.exe click Ok


Now we create a proxy class of our service. So create a class name MyCalculatorServiceProxy.cs
Add a namespace WCfSelfHostingService of this proxy class.
MyCalculatorServiceProxy.cs code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using WCfSelfHostingService;
namespace WCfSelfHostingClient
{
    class MyCalculatorServiceProxy : ClientBase, ICalculatorService
    {
        public int Add(int a, int b)
        {
            return base.Channel.Add(a, b);
        }
    }
}
We need to add End Point in App.config file following below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <system.serviceModel>
    <client>
      <endpoint address ="http://localhost:8007/WCfSelfHostingService/CalculatorService"
                binding ="basicHttpBinding"
                contract ="WCfSelfHostingService.ICalculatorService">
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>
Now open Program.cs file and add a namespace WCfSelfHostingService and modify like below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCfSelfHostingService;
namespace WCfSelfHostingClient
{
    class Program
    {
        static void Main(string[] args)
        {
            MyCalculatorServiceProxy proxy;
            proxy = new MyCalculatorServiceProxy();
            Console.WriteLine("Client is running at " + DateTime.Now.ToString());
            Console.WriteLine("Sum of two numbers... 15+25 =" + proxy.Add(15, 25));
            Console.ReadLine();
        }
    }
}
Now run the application. We can see the screen like below:


So service is working fine. Enjoy!

Error: 1

If you getting an error like below image. Make sure that service is running.


Error: 2

If you getting an error like below image. Make sure that you add End point in client application.


Download

You can download this application zip file here

Conclusion

I hope this will be helpful.

You Might Also Like

0 comments