Как добавить поведение к конечной точке клиента в IIS Hosted WCF Service, используя ServiceHostFactory

Я смотрю на реализацию IDispatchMessageInpector & IClientMessageInpector для просмотра объектов сообщения в методах AfterReceiveRequest и BeforeSendRequest. Мое требование - вносить изменения на уровне кода службы WCF. Нет изменений конфигурации. Как подключить это поведение ко всем конечным точкам, которые вызывают эту услугу, и обслуживать себя. Помогает ли мне внедрение IContractBehaviour?

Изменить 1: Служба WCF размещена на IIS. Можно ли добавить поведение через код?

Редактировать 2: Кажется, с помощью ServiceHostFactory мы можем достичь этого. Как я могу добавить поведение к конечной точке клиента, которая определена в webconfig?

2 ответа

Да, можно добавить поведение для служб, размещенных в IIS. Поведения не касаются среды размещения службы. Блог Карлоса Фигейры содержит примеры всех типов поведения, которые вы можете применить к Сервису, Конечным точкам, Контрактам и Операциям. Пример кода, который я пробовал для моей службы, размещенной в IIS (с конечной точкой, определенной в файле web.config). В файле конфигурации необходимо добавить поведение в качестве ExtensionElement

public class MyEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior
{
            public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
            {
                Console.WriteLine("applying dispatch behavior");
                endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyInspector());
                endpointDispatcher.DispatchRuntime.OperationSelector = new MyOperationSelector();
            }

        public void  AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

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

        public void  Validate(ServiceEndpoint endpoint)
        {
        }

        public override Type BehaviorType
        {
            get {  return this.GetType(); }
        }

        protected override object CreateBehavior()
        {
           return new MyEndpointBehavior();
        }
}

    public class MyOperationSelector : IDispatchOperationSelector
    {
        public string SelectOperation(ref Message message)
        {
            Console.WriteLine("good luck");
            string action = message.Headers.Action;
            return action.Substring(action.LastIndexOf('/') + 1);
        }
    }

    public class MyInspector : IDispatchMessageInspector
    {

        public object AfterReceiveRequest(ref Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            return (Message) request;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
        }
    }
 }

Файл конфигурации с поведением, добавленным в качестве элемента расширения -

  <system.serviceModel>
  <services>
  <service name="RouteToServiceA.Service1">
    <endpoint address="Service1" binding="basicHttpBinding" contract="RouteToServiceA.IService1" behaviorConfiguration="testEndPoint" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="true" />
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="testEndPoint">
      <testBehavior />
    </behavior>
  </endpointBehaviors>
</behaviors>
<extensions>
  <behaviorExtensions>
    <add name="testBehavior" type="RouteToServiceA.MyEndpointBehavior, RouteToServiceA" />
  </behaviorExtensions>
</extensions>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 </system.serviceModel>

Используя ServiceHostFactory, мы можем добавить поведение службы, тогда как добавление конфигурации поведения к конечным точкам клиента, которые находятся в конфигурации, кажется невозможным. Так что я иду с изменениями конфигурации

Другие вопросы по тегам