Click here to Skip to main content
15,881,559 members
Articles / Web Development / ASP.NET

WCF Hosting with Windows Service

Rate me:
Please Sign up or sign in to vote.
4.85/5 (38 votes)
30 Sep 2013CPOL8 min read 219K   23.6K   80  
This article explains how to host a WCF library in a Windows Service.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using WCFCalcLib;

namespace WCFHostedWindowsService
{
    public partial class MyCalcWinService : ServiceBase
    {
        ServiceHost m_svcHost = null ;

        public MyCalcWinService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (m_svcHost != null) m_svcHost.Close();
                
            string strAdrHTTP = "http://localhost:9001/CalcService";
            string strAdrTCP = "net.tcp://localhost:9002/CalcService";

            Uri[] adrbase = { new Uri(strAdrHTTP), new Uri(strAdrTCP) };
            m_svcHost = new ServiceHost(typeof(WCFCalcLib.CalcService), adrbase);

            ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior();
            m_svcHost.Description.Behaviors.Add(mBehave);

            BasicHttpBinding httpb = new BasicHttpBinding();
            m_svcHost.AddServiceEndpoint(typeof(WCFCalcLib.ICalcService), httpb, strAdrHTTP);
            m_svcHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

            NetTcpBinding tcpb = new NetTcpBinding();
            m_svcHost.AddServiceEndpoint(typeof(WCFCalcLib.ICalcService), tcpb, strAdrTCP);
            m_svcHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

            m_svcHost.Open();
        }

        protected override void OnStop()
        {
            if (m_svcHost != null)
            {
                m_svcHost.Close();
                m_svcHost = null;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
More than 10 years of experience in designing and development of GUIs and Middleware for industrial control systems.

Comments and Discussions