2011-09-23 3 views
4

각 작업 전에 실행될 WCF 서비스에 대한 DispatchMessageInspector를 만들고 일부 처리를 수행 한 다음 해당 처리의 결과를 작업에 사용할 수있게하려고합니다.WCF DispatchMessageInspector - 작업 처리 및 사용 가능

MessageInspector 만들기는 쉽습니다. 그러나 내가 수행해야하는 작업을 수행 한 후, 생성 한 객체를 어디에 배치하여 각 작업의 코드에서 액세스 할 수 있습니까? MessageInspector에서 OperationConext에 저장하겠습니까? 아니면 더 깨끗한 솔루션이 있습니까?

답변

4

일반적으로 메시지 속성에이 정보를 저장 한 다음 작업의 작업 컨텍스트를 통해 액세스합니다 (아래 코드의 예 참조).

public class StackOverflow_7534084 
{ 
    const string MyPropertyName = "MyProp"; 
    [ServiceContract] 
    public interface ITest 
    { 
     [OperationContract] 
     string Echo(string text); 
    } 
    public class Service : ITest 
    { 
     public string Echo(string text) 
     { 
      Console.WriteLine("Information from the inspector: {0}", OperationContext.Current.IncomingMessageProperties[MyPropertyName]); 
      return text; 
     } 
    } 
    public class MyInspector : IEndpointBehavior, IDispatchMessageInspector 
    { 
     public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) 
     { 
     } 

     public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) 
     { 
     } 

     public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
     { 
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this); 
     } 

     public void Validate(ServiceEndpoint endpoint) 
     { 
     } 

     public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) 
     { 
      request.Properties[MyPropertyName] = "Something from the inspector"; 
      return null; 
     } 

     public void BeforeSendReply(ref Message reply, object correlationState) 
     { 
     } 
    } 
    public static void Test() 
    { 
     string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
     ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); 
     host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "").Behaviors.Add(new MyInspector()); 
     host.Open(); 
     Console.WriteLine("Host opened"); 

     ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress)); 
     ITest proxy = factory.CreateChannel(); 
     Console.WriteLine(proxy.Echo("Hello")); 

     ((IClientChannel)proxy).Close(); 
     factory.Close(); 

     Console.Write("Press ENTER to close the host"); 
     Console.ReadLine(); 
     host.Close(); 
    } 
} 
관련 문제