[WCF]WCF Overload Method

  • 2703
  • 0
  • WCF
  • 2011-10-17

[WCF]WCF Overload Method

在WCF中Method如何做Overload呢?

可以透過OperationContract設定不同的Name來達成,如下

[ServiceContract]
public interface IService1
{
    [OperationContract(Name="AddInt")]
    int Add(int arg1, int arg2);

    [OperationContract(Name = "AddDouble")]
    double Add(double arg1, double arg2);
}

public class Service1 : IService1
{
    public int Add(int arg1, int arg2)
    {
        return arg1 + arg2;
    }

    public double Add(double arg1, double arg2){
        return arg1 + arg2;
    }
}

那Client要呼叫時,會變成AddInt及AddDouble,所以如果要讓Client去Call Overload Method的話,就要改一下proxy的Code,

跟Service一樣,在OperationContractAttribute加入Name,再把Method改成Add,Clicnt也改成Channel.Add如下,

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="WCFSvc.IService1")]
public interface IService1 {
    [System.ServiceModel.OperationContractAttribute(Name = "AddInt", Action="http://tempuri.org/IService1/AddInt", ReplyAction="http://tempuri.org/IService1/AddIntResponse")]
    int Add(int arg1, int arg2);
    
    [System.ServiceModel.OperationContractAttribute(Name = "AddDouble", Action="http://tempuri.org/IService1/AddDouble", ReplyAction="http://tempuri.org/IService1/AddDoubleResponse")]
    double Add(double arg1, double arg2);
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class Service1Client : System.ServiceModel.ClientBase<WindowsFormsApplication1.WCFSvc.IService1>, WindowsFormsApplication1.WCFSvc.IService1 {
    
    public Service1Client() {
    }
    
    public Service1Client(string endpointConfigurationName) : 
            base(endpointConfigurationName) {
    }
    
    public Service1Client(string endpointConfigurationName, string remoteAddress) : 
            base(endpointConfigurationName, remoteAddress) {
    }
    
    public Service1Client(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(endpointConfigurationName, remoteAddress) {
    }
    
    public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
            base(binding, remoteAddress) {
    }

    public int Add(int arg1, int arg2) {
        return base.Channel.Add(arg1, arg2);
    }
    
    public double Add(double arg1, double arg2) {
        return base.Channel.Add(arg1, arg2);
    }
}

這樣在呼叫時WCF Service就有Overload Method了!

WCFSvc.Service1Client proxy = new WCFSvc.Service1Client();
MessageBox.Show(proxy.Add(1, 2).ToString());
MessageBox.Show(proxy.Add(1.45, 2.33).ToString());

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^