WCF - How to publish service with TCP binding

参考资料:How to: Publish Metadata for a Service Using Code

using (ServiceHost host = new ServiceHost(typeof(FileService))) {
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
    host.Description.Behaviors.Add(smb);
 
    host.AddServiceEndpoint(
        ServiceMetadataBehavior.MexContractName,
        MetadataExchangeBindings.CreateMexTcpBinding(),
        "net.tcp://localhost:8080/syncup/mex"
    );
    host.AddServiceEndpoint(typeof(IFileService), new NetTcpBinding(), "net.tcp://localhost:8080/syncup");
 
    host.Open();
 
    Console.WriteLine("Syncup Server is started.");
    Wait();
 
    host.Close();
}

注:只有添加了ServiceMetadataBehavior才能支持IMetadataExchange接口,否则会抛出InvalidOperationException异常:

The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MyService.  Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.