在WCF服务中,通常需要提供终结点地址来连接到服务。但是有时候,我们可能希望在不提供终结点地址的情况下连接到WCF服务。以下是一个解决方法的代码示例:
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetData(int value);
}
public class MyService : IMyService
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
public class Program
{
    static void Main(string[] args)
    {
        // 创建服务主机
        using (ServiceHost host = new ServiceHost(typeof(MyService)))
        {
            // 添加终结点
            host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), "net.tcp://localhost/MyService");
            // 允许基于代码的配置
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);
            // 启动服务
            host.Open();
            Console.WriteLine("Service is running...");
            Console.ReadLine();
            // 关闭服务
            host.Close();
        }
    }
}
using System;
using System.ServiceModel;
public class Program
{
    static void Main(string[] args)
    {
        // 创建通道工厂
        ChannelFactory factory = new ChannelFactory(new NetTcpBinding());
        // 创建通道
        IMyService channel = factory.CreateChannel(new EndpointAddress("net.tcp://localhost/MyService"));
        // 调用服务方法
        string result = channel.GetData(42);
        Console.WriteLine(result);
        // 关闭通道和工厂
        ((IClientChannel)channel).Close();
        factory.Close();
        Console.ReadLine();
    }
}
  
通过上述方法,我们可以在不提供终结点地址的情况下成功连接到WCF服务。