9

What is the best practice for emulating overloaded methods over WCF?

Typically I might write an interface like this

interface IInterface 
{
    MyType ReadMyType(int id);
    IEnumerable<MyType> ReadMyType(String name);
    IEnumerable<MyType> ReadMyType(String name, int maxResults);    
}

What would this interface look like after you converted it to WCF?

Nate
  • 30,286
  • 23
  • 113
  • 184
  • possible duplicate of [Why method overloading is not allowed in WCF?](http://stackoverflow.com/questions/10276124/why-method-overloading-is-not-allowed-in-wcf) – Michael Freidgeim Feb 02 '15 at 00:52

2 Answers2

10

You can leave it like that if you like. Just use the name property of the OperationContract attribute.

[ServiceContract]
interface IInterface 
{
    MyType ReadMyType(int id);
    [OperationContract(Name= "Foo")]
    IEnumerable<MyType> ReadMyType(String name);
    [OperationContract(Name= "Bar")]
    IEnumerable<MyType> ReadMyType(String name, int maxResults);    
}
mwilson
  • 1,255
  • 12
  • 17
  • What would that look like I'm not familiar with that? – Nate May 06 '10 at 19:37
  • 2
    This works, although this can be really painful to keep up with, trace, debug, etc... Depending on the connecting products (E.g. Basic Profile, etc) you can still run in to problems. Although it feels strange to class developers it may be better to just use more expressive names and not have to maintain two seperate taxonomies – JoeGeeky May 13 '10 at 20:22
  • Joe is right, which is precisely why the best practice is to name methods uniquely and not overload them. That being said, the answer is good, just not best practice. :) – Chiramisu Jan 10 '13 at 11:01
5

As mwilson already said - WCF doesn't allow methods to have the same name in the service definition (the WSDL).

If you have two or more (overloaded) methods with the same name in .NET, you need to disambiguate them for the WCF service definition by specifying a Name= on the [OperationContract] attribute for each method.

Remember: WCF is not .NET (or not .NET alone) - it's an interoperable standard, and the WSDL standard does not currently support method overloading - each method must be uniquely identifyable by name.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459