wcf Your first service Programmatically adding a metadata endpoint to a service


When you also want to expose metadata without a config file you can build on the example programmatically creating a ServiceHost:

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

    NetTcpBinding tcp = new NetTcpBinding();

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

    ServiceMetadataBehavior metaBehavior = mHost.Description.Behaviors.Find<ServiceMetadataBehavior>();

    if (metaBehavior == null)
        metaBehavior = new ServiceMetadataBehavior();
        metaBehavior.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        metaBehavior.HttpGetEnabled = true;

        mHost.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

  1. Create a ServiceHost instance passing the concrete class type and zero or more baseaddress Uri's.
  2. When you use mexHttpBinding you have to add http://localhost:8000/Example baseaddress
  3. Construct the desired binding, NetTcpBinding in this case.
  4. call AddServiceEndpoint passing the Address, Binding and Contract. (ABC).
  5. Construct a ServiceMetadataBehavior
  6. Set HttpGetEnabled to true
  7. Add the metadata behavior to the behaviors collection.
  8. call AddServiceEndpoint passing the constants for metadata exchange
  9. Open the host.