b

Wednesday 23 January 2013

Self Hosting WCF Service C#

Self Hosting WCF Service in Console Applictaion


1) Create Contract and Implementation
     Here I use ADO.NET connecting to Northwind Database to get Number of Orders.

2) In Program Entry.
              Create Service Host  
3) Using ChannelFactory query above WCF Service

ServiceContract

    [ServiceContract]
    public interface IOrder
    {
        [OperationContract]
        int GetOrderCount();
    }

Implementation Class for Service Contract
Service Contract has single method called GetOrderCount from NorthWind Database.
 
    public class Orders : IOrder
    {
        public int GetOrderCount()
        {
            SqlConnection conn = new
                SqlConnection(@"Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;");
            conn.Open();

            SqlCommand cmd = new SqlCommand("select count(*) from orders",conn);
            object obj=cmd.ExecuteScalar();

           return Int32.Parse(obj.ToString());
        }
 

In Program Entry Point

                1) Create/Host a WCF Service  assign some port number(unused) here

                 2) Consume same service using ChannelFactory


                1) Create/Host a WCF Service  assign some port number(unused) here

                //Create or Host WCF Service Here
                Uri[] baseAdd = new Uri[] { new Uri("http://localhost:7070/") };
                ServiceHost host = new ServiceHost(typeof(Orders), baseAdd);
                host.AddServiceEndpoint(typeof(IOrder), new WSHttpBinding(),
                "http://localhost:7070/selfhost");

                ServiceMetadataBehavior mb = new ServiceMetadataBehavior();
                mb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(mb);

                host.Open(); //Open the Service
 
                 2) Consume same service using ChannelFactory

               //Consume the above WCF Service using ChannelFactory
                //
                WSHttpBinding binding = new WSHttpBinding();
                EndpointAddress address = new EndpointAddress("http://localhost:7070/selfhost");

                selfhostwcf.IOrder channel = new ChannelFactory<selfhostwcf.IOrder>(
               binding, address).CreateChannel();
                Console.WriteLine("Order Count={0}",channel.GetOrderCount());

                Console.ReadLine();

That's it ,Hosting and consuming WCF service in console application without web.config settings.


Type :  
http://localhost:7070/  in your browser u will see metadata.

as long as console application is running you can access service metdata and other applications also can consume this service.


After Excuting Console Application U will get Output as
Order Count=830


Complete Source Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel.Channels;
namespace selfhostwcf
{

    [ServiceContract]
    public interface IOrder
    {
        [OperationContract]
        int GetOrderCount();
    }

    public class Orders : IOrder
    {
        public int GetOrderCount()
        {
            SqlConnection conn = new
                SqlConnection(@"Data Source=localhost\sqlexpress2012;Initial Catalog=northwind;trusted_connection=yes;");
            conn.Open();

            SqlCommand cmd = new SqlCommand("select count(*) from orders",conn);
            object obj=cmd.ExecuteScalar();

           return Int32.Parse(obj.ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //Create or Host WCF Service Here
                Uri[] baseAdd = new Uri[] { new Uri("http://localhost:7070/") };
                ServiceHost host = new ServiceHost(typeof(Orders), baseAdd);
                host.AddServiceEndpoint(typeof(IOrder), new WSHttpBinding(),
                "http://localhost:7070/selfhost");

                ServiceMetadataBehavior mb = new ServiceMetadataBehavior();
                mb.HttpGetEnabled = true;
                host.Description.Behaviors.Add(mb);

                host.Open(); //Open the Service


                //Consume the above WCF Service using ChannelFactory
                //
                WSHttpBinding binding = new WSHttpBinding();
                EndpointAddress address = new EndpointAddress("http://localhost:7070/selfhost");

                selfhostwcf.IOrder channel = new ChannelFactory<selfhostwcf.IOrder>(binding, address).CreateChannel();
                Console.WriteLine("Order Count={0}",channel.GetOrderCount());

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
          
        }
    }
}
 
Tags:Self Hosting WCF Service,ado.net in wcf service,
Hosting and consuming WCF service in console application without web.config,WCF Service contract,WCF Operation contract,Host service in console applictaion,Consume WCF service using ChannelFactory,Consume WCF service using ChannelFactory in console application

No comments:

Post a Comment