WCF - ChannelFactory

在学习和测试 WCF 的时候,我通常使用 ChannelFactory 来代替 Client Proxy。原因是方便,无须创建多个 Project / Class。当然,在正式开发中还是使用 Client Proxy 要好些,毕竟 ChannelFactory 直接依赖于契约,违背了 SOA 边界隔离的原则。

使用 ChannelFactory 很简单,但完成方法后要及时调用 Close 或 Dispose,以便服务器及时释放服务实例。你没有找到这两个方法? [smile] 其实该对象还实现了另外两个接口 —— IDisposable 和 ICommunicationObject。

代码演示
[ServiceContract]
public interface IContract
{
  [OperationContract]
  void Test(int i);
}

public class MyService : IContract
{
  public void Test(int i)
  {
    Console.WriteLine(i);
  }
}

public class WcfTest
{
  public static void Test()
  {
    AppDomain.CreateDomain("Server1").DoCallBack(delegate
    {
      ServiceHost host = new ServiceHost(typeof(MyService), new Uri("http://localhost:8080/MyService"));
      host.AddServiceEndpoint(typeof(IContract), new BasicHttpBinding(), "");
      host.Open();
    });

    IContract channel = ChannelFactory<IContract>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8080/MyService"));

    using (channel as IDisposable)
    {
      ICommunicationObject o = channel as ICommunicationObject;

      o.Opening += delegate { Console.WriteLine("Opening..."); };
      o.Closing += delegate { Console.WriteLine("Closing..."); };

      channel.Test(1);
    }
  }
}

posted on 2008-11-06 13:22  topzengyi  阅读(679)  评论(0)    收藏  举报

导航