wcf Your first service Create a ServiceHost programmatically


Example

Creating a ServiceHost programmatically (without config file) in its most basic form:

namespace ConsoleHost
{
  class ConsoleHost
  {
    ServiceHost mHost;

    public Console()
    {
      mHost = new ServiceHost(typeof(Example), new Uri("net.tcp://localhost:9000/Example"));

      NetTcpBinding tcp = new NetTcpBinding();

      mHost.AddServiceEndpoint(typeof(IExample),tcp,"net.tcp://localhost:9000/Example");                      
    }

    public void Open()
    {
        mHost.Open();
    }
    
    public void Close()
    {
        mHost.Close();
    }

    public static void Main(string[] args)
    {
        ConsoleHost host = new ConsoleHost();
        
        host.Open();
        
        Console.ReadLine();
        
        host.Close();
    }
  }
}
  1. Create a ServiceHost instance passing the concrete class type and zero or more baseaddress Uri's.
  2. Construct the desired binding, NetTcpBinding in this case.
  3. call AddServiceEndpoint passing the Address, Binding and Contract. (ABC mnemonic for WCF endpoints).
  4. Open the host.
  5. Keep host open until user press key on console.
  6. Close the host.