当前位置: 首页 > 工具软件 > TChannel > 使用案例 >

ChannelFactory<TChannel> 类

潘俊
2023-12-01


一个创建不同类型通道的工厂,客户端使用这些通道将消息发送到不同配置的服务终结点。


示例


下面的示例演示如何创建通道工厂并用它来创建和管理通道。

C#
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();

下面的代码示例演示如何在工厂创建通道对象前,以编程方式插入客户端行为。

C#
VB
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();
    }
  }
 类似资料: