寺委书记

Good good study, day day up!

导航

WCF双工(Duplex)回调函数契约接口不可继承的现象

Posted on 2011-01-06 10:46  MonkChen  阅读(736)  评论(0)    收藏  举报

昨天发现一个现象, WCF 回调接口不可直接继承,它的直接继承体系只能有一层,这话怎么说都别扭,还是举例说明吧:

 

1.WCF 服务契约接口可以继承,伪代码如下:

 

代码
 同时,你设计了一个实现类

public class ServiceBase : IServiceBase
{
   
public void FooBase()
    {
    
//Do something here
    }
}

由于业务的需要,你需要扩展服务接口,于是设计一个新接口

public interface IService : IServiceBase //继承自IServiceBase接口
{
      [OperationContract(IsOneWay
=true)]
      
void Foo(); 
}

同时有了新的实现类

public class Service
{
    
public void Foo()
   {
       
//Do Something Here
   }
}

 

 

接着就可以发布服务了:

 ServiceHost host = new ServiceHost(typeof(Service));                     
  host.Open();

 

此种方式是合法的,一切OK,以此类推,我们来设计一下回调接口:

 

代码
public interface ICallbackBase
{
    [OperationContract(IsOneWay
=true)]
    
void FooCallbackBase();
}
 
//由于业务的需要,你要接着来。。。

public interface ICallback : ICallbackBase
{
    [OperationContract(IsOneWay
=true)]
    
void FooCallback();
}

//由于业务的需要,你需要双工,于是调用了回调接口
[ServiceContract(CallbackContract = typeof(ICallback))]
public interface IService : IServiceBase
{
   [OperationContract(IsOneWay
=true)]
  
void Foo();
}

//当然,你会在实现类调用回调
public class : IService
{
   
public void Foo()
   {
       
//Do something here
       ICallback icallback = OperationContext.Current.GetCallbackChannel<ICallback >();
       
try
       {
          icallback.FooCallback();
          icallback.FooCallbackBase();
       }
       
catch(Exception ex)
       {
           
//handle exception here
       }  
   }
}

//没有语法错误,编译通过运行

 


可是当你的客户端调用Foo的时候,异常却偏偏出现了:
Callback method FooCallbackBase is not supported, this can happen if the method is not marked with OperationContractAttribute or if its interface type is not the target of the ServiceContractAttribute's CallbackContract.

(本人用的是英文版vs2010,因为出现问题也是英文的,比较容易google)

 

接着你可以做个测试,把ICallback改成如下:

 

public interface ICallback  
{
   [OperationContract]
   
void FooCallbackBase();  
   
   [OperationContract(IsOneWay
=true)]
    
void FooCallback();
}

 

 

 再运行,你的程序就变得和谐了。。。可是你依然不爽,总有点怪怪的感觉

从现象得出结论:(该结论很长,各位自己归纳),这点和WCF服务接口有所区别。

 出现问题就要解决,google出这个帖子http://social.msdn.microsoft.com/Forums/en/wcf/thread/ef896836-dec1-4fa6-9956-e3a4958643ce

各位自己看去吧