4

I am implementing a .Net WCF service and I want to apply a namespace for future versioning. A coworker mentioned that I ought to apply several attributes to both the interface and the concrete implementation class for that interface, but it is not clear to me 1) if this is correct, and 2) assuming it is correct, why it would be important to apply the attributes in both places.

[ServiceContract]
[ServiceBehavior(Namespace = Constants.NameSpace1_0)]
[WebService(Namespace = Constants.NameSpace1_0, Name = "MyService1_0")]
[WebServiceBindingAttribute(ConformsTo = System.Web.Services.WsiProfiles.BasicProfile1_1, EmitConformanceClaims = true)]
public interface IMyService
{
    [OperationContract]
    [OperationContract(Name = "MyMethod", Action = Constants.NameSpace1_0 + "/IMyService/MyMethod")]  
    string MyMethod(string phrase);
}

public class MyServiceConcrete : IMyService
{
    public string MyMethod(string phrase);
}

In this example, should I also apply the attributes that are applied to the interface to the concrete class (and its methods) that implements the MyService interface? Should I apply the same attributes in both places or just one of the places, and why? Thanks.

Shawn
  • 8,374
  • 5
  • 37
  • 60

1 Answers1

0

You only need to apply the service attributes to the interface. The interface, and only the interface, is used by WCF to define the API - the implementation always implements all interface members, so the attributes are not needed there. Attributes on the concrete implementation will just get ignored.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 3
    according to msdn http://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.aspx the service attribute can be applied to eather an interface or directly to a class . the question here is relly the pros and cons of one over the other for instance if your service exposes multiple contracts you have to do add the attribute to each interface so as to allow multiple contracts to be implemented – eran otzap Mar 26 '12 at 20:06
  • You can't apply a ServiceBehavior attribute to an interface, it's valid on class declaration only, as per .net 4.5 – Oscar Dec 16 '16 at 08:06