title: Add Message Inspector to WCF service in code rather that config file
body: <p>I working through an example from Microsoft training kit (WCF). It entails adding Message Inspection to a service. </p>
  
  <p>I have thus far create the inspection implementation class, message behavior class and a message behavior class extension. </p>
  
  <p>Instead of adding the behavior through the config file I would like to add it in the service host file. Below are the implementation classes...</p>
  
  <pre><code> public class MessageTrace : IDispatchMessageInspector
      {
          private Message TraceMessage(MessageBuffer buffer)
          {
              Message msg = buffer.CreateMessage();
              StringBuilder sb = new StringBuilder("Message content");
              sb.Append(msg.ToString());
              Console.WriteLine(sb.ToString());
              return buffer.CreateMessage();
          }
  
          public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
          {
              request = TraceMessage(request.CreateBufferedCopy(Int32.MaxValue));
              return null;
          }
  
          public void BeforeSendReply(ref Message reply, object correlationState)
          {
              reply = TraceMessage(reply.CreateBufferedCopy(Int32.MaxValue));
          }
      }
  
  public class TraceMessageBehavior : IEndpointBehavior
      {
          public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
          {}
  
          public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
          {}
  
          public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
          {
              MessageTrace inspector = new MessageTrace();
              endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
          }
  
          public void Validate(ServiceEndpoint endpoint)
          {}
      }
  
   public class TraceMessageBehaviorExtension : BehaviorExtensionElement
      {
          public override Type BehaviorType
          {
              get { return typeof(TraceMessageBehavior); }
          }
  
          protected override object CreateBehavior()
          {
              return new TraceMessageBehavior();
          }
      }
  </code></pre>