Tuesday, 10 March 2015

Hosting WCF services in console application

Adding and hosting WCF services in console application

1. Create a New "class library" project and add a new item in this project as "wcf service"
2. Add the new "console project" in your solution
3.Add the service refernece to your "console project"
4.Add the system.servicemodel reference to your project
5.Add the "app.config" to your project
6.Code "App.config" as :-
//<App.config>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="namespace.Name_of_Service" behaviorConfiguration="Name_of_behavior">
        <endpoint address="Name_of_Service" binding="basicHttpBinding" contract="namespace.Name_of_ServiceInterface"></endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/"/>
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="Name_of_behavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>

7.Make your "console project" as startup project and code the program.cs as :-

 public static void Main(string[] args)
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(Namespace.Name_of_Service)))
                {
                    host.Open();
                    Console.WriteLine("Host started @" + DateTime.Now.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

No comments:

Post a Comment