6

可能重复:
为什么不能重载 WCF 中的方法?

我正在开发一个使用 WCF 服务的项目。我的问题是,在 WCF 服务中,我有一个名为Display()client1 的方法。

现在我想添加另一种具有相同名称但具有一个参数的方法,即。Display(string name), 这样新的 clinet2 可以使用新方法,旧的 client1 可以使用旧方法。我怎样才能做到这一点?这是我编写的代码。

namespace ContractVersioningService
{
  [ServiceContract]
  public interface IService1 
  {
    [OperationContract]
    string Display();

    [OperationContract]
    string GoodNight();
  }     
}

namespace ContractVersioningService
{
   public class Service1 : IService1
   {
     public string Display()
     {
        return "Good Morning";          
     }

     public string GoodNight()
     {
        return "Good Night";
     }
   }
}    

namespace ContractVersioningService
{
  [ServiceContract(Namespace = "ContractVersioningService/01", Name =      "ServiceVersioning")]
  public interface IService2 : IService1
  {
     [OperationContract]
     string Disp(string greet);
  }
}

namespace ContractVersioningService
{
 
   public class Service2 : Service1, IService2
   {
      public string Display(string name)
      {
         return name;
      }

      public string Disp(string s)
      {
         return s;
      }
   }
}
4

2 回答 2

13
    Why WCF doesnot support method overloading directly ?
  • 因为 WSDL 不支持方法重载(不是 OOP)。WCF 生成 WSDL,它指定服务的位置以及服务公开的操作或方法。

    WCF 使用 Document/Literal WSDL Style:微软提出了这个标准,soap body 元素将包含 web 方法名称。

  • 默认情况下,所有 WCF 服务都符合文档文字标准,soap 主体应包含方法名称。

    唯一的方法是使用 Name 属性。例如,

        [OperationContract(Name="Integers")]
        int Display(int a,int b)
        [OperationContract(Name="Doubles")]
        double Display(double a,double b)
    

编译器将生成以下内容,这对于 wsdl 定位是有意义的

     [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName=
    "ServiceRef.IService1")]
  public interface IService1
   {
       [System.ServiceModel.OperationContractAttribute(
       Action="http://tempuri.org/Service1/AddNumber",
       ReplyAction="http://tempuri.org/IHelloWorld/IntegersResponse")]                   
       int Display(int a,int b)

       [System.ServiceModel.OperationContractAttribute(
       Action="http://tempuri.org/IHelloWorld/ConcatenateStrings",
       ReplyAction="http://tempuri.org/Service1/DoublesResponse")]
       double Display(double a,double b)
  }
于 2013-01-23T06:49:56.830 回答
7

好的,我要回答这个问题,因为现在评论变得过度了。

你基本上有两个选择:

  • 使用单个接口(请注意,接口继承,就像您在问题中建议的那样,在技术上算作一个接口),但是您必须为每个服务操作指定一个不同的名称。您可以通过将 C# 方法命名为不同的方法,或者通过应用[OperationContract(Name = "distinctname")]属性来做到这一点。

  • 使用两个独立的接口,它们之间没有任何继承关系,将每个接口发布在不同的端点上。然后,您可以在每个中都有一个服务操作,具有相同的名称,但具有不同的参数。当然,如果您愿意/需要,您仍然可以使用一个实现类来实现这两个接口。

于 2013-01-23T06:28:08.963 回答