Mixing Message Contract Attributes

What's wrong with the following code? The error message when you try this is better than it used to be a few months ago. However, since you don't see the error until you try to run your service, I still see people making this mistake.

 [MessageContract]
public class MyMessage
{
   [MessageBodyMember]
   public string name;
}

[ServiceContract]
public interface IService
{
   [OperationContract]
   string Method(MyMessage message);
}

public class Service : IService
{
   public string Method(MyMessage message)
   {
      return "Hello: " + message.name;
   }
}

The problem is that message contracts cannot be used at the same time as other parameter types. In this case, the return value of the operation is a string. Return values are just another output parameter, so this operation is mixing a message contract message with a primitive parameter type. This fails because message contracts give you control of the layout of the SOAP message, preventing the system from melding in these additional parameters.

By the way, the error message you get when you try to mix message contracts looks like this.

System.InvalidOperationException: The operation 'Method' could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message or a type that has MessageContractAttribute and other parameters of different types. When using System.ServiceModel.Channels.Message or types with MessageContractAttribute, the method must not use any other types of parameters.

Next time: Controlling the Synchronization Context