ChannelFactory<TChannel> 类 一个创建不同类型通道的工厂,客户端使用这些通道将消息发送到不同配置的服务终结点。 命名空间: System.ServiceModel 语法 public class ChannelFactory<TChannel> : ChannelFactory, IChannelFactory<TChannel>, IChannelFactory, ICommunicationObject 类型参数 TChannel 由通道工厂生成的通道类型。 此类型必须为 IOutputChannel 或 IRequestChannel。 备注 使用此泛型类可实现一些更高级的方案,在这些方案中有创建通道工厂(可用于创建多个通道类型)的要求。 以编程方式添加行为时,可以在创建任何通道之前将行为添加到 Behaviors 上相应的 ChannelFactory 属性。 有关代码示例,请参见“示例”部分。 /// <summary> /// 下面的示例演示如何创建通道工厂并用它来创建和管理通道 /// </summary> public static void Main() { BasicHttpBinding binding = new BasicHttpBinding(); EndpointAddress address = new EndpointAddress("http://localhost:8000/ChannelApp"); ChannelFactory<IRequestChannel> factory = new ChannelFactory<IRequestChannel>(binding, address); IRequestChannel channel = factory.CreateChannel(); channel.Open(); Message request = Message.CreateMessage(MessageVersion.Soap11, "hello"); Message reply = channel.Request(request); Console.Out.WriteLine(reply.Headers.Action); reply.Close(); channel.Close(); factory.Close(); } /// <summary> /// 下面的代码示例演示如何在工厂创建通道对象前,以编程方式插入客户端行为。 /// </summary> public class Client { public static void Main() { try { // Picks up configuration from the config file. ChannelFactory<ISampleServiceChannel> factory = new ChannelFactory<ISampleServiceChannel>("WSHttpBinding_ISampleService"); // Add the client side behavior programmatically to all created channels. factory.Endpoint.Behaviors.Add(new EndpointBehaviorMessageInspector()); ISampleServiceChannel wcfClientChannel = factory.CreateChannel(); // Making calls. Console.WriteLine("Enter the greeting to send: "); string greeting = Console.ReadLine(); Console.WriteLine("The service responded: " + wcfClientChannel.SampleMethod(greeting)); Console.WriteLine("Press ENTER to exit:"); Console.ReadLine(); // Done with service. wcfClientChannel.Close(); Console.WriteLine("Done!"); } catch (TimeoutException timeProblem) { Console.WriteLine("The service operation timed out. " + timeProblem.Message); Console.Read(); } catch (FaultException<SampleFault> fault) { Console.WriteLine("SampleFault fault occurred: {0}", fault.Detail.FaultMessage); Console.Read(); } catch (CommunicationException commProblem) { Console.WriteLine("There was a communication problem. " + commProblem.Message); Console.Read(); } }