Developer Geeks Home
 

How to Self Host a WCF Service

RSS

  • Posted one year ago
  • Language: C#
  • Tags: C#, Self Hosting, WCF Service

Sample code: How to Self Host a WCF Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHostingWCF
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string HelloWorld(string name);
    }

    public class HelloWorldService : IHelloWorldService
    {
        public string HelloWorld(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8080/helloworld");

            // Create the ServiceHost.
            using (ServiceHost servicehost = new ServiceHost(typeof(HelloWorldService), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior metadata = new ServiceMetadataBehavior();
                metadata.HttpGetEnabled = true;
                metadata.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                servicehost.Description.Behaviors.Add(metadata);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                servicehost.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                servicehost.Close();
            }
        }
    }
}
comments powered by Developer Geeks