0

我正在尝试使用路由服务(http://msdn.microsoft.com/en-us/library/ee517422.aspx)将数据从客户端路由到其他端点。我有多个客户端,并且从路由服务调用的端点位于第三方。

我还需要将通过路由服务传递的每个事务记录到 SQL 数据库中。

问题是我无法在路由服务中编写自定义代码,因为它是通过配置文件工作的。鉴于我无法在这些类中编写自定义代码,我该如何实现呢?

4

1 回答 1

0

1)创建一个类库并用强密钥对其进行签名。

2)创建RoutingServiceBehavior类 该类将实现IServiceBehavior、IDispatchMessageInspector接口,消息拦截代码在该类中:

using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace Services.RoutingServiceBehavior
{
    public class RoutingServiceBehavior : IServiceBehavior, IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            // This is your envelop
            string s = request.ToString();
            return null;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {

        }

        public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {

        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
            {
                foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
                {
                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
                }
            }  

        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }
    }
}

3)创建RoutingServiceBehaviorElement类,该类将实现BehaviorExtensionElement接口:

using System;
using System.ServiceModel.Configuration;

namespace Services.RoutingServiceBehavior
{
    public class RoutingServiceBehaviorElement : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(RoutingServiceBehavior); }
        }

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

4)构建你的项目。
5)将您的程序集添加到 GAC。
6)打开 machine.config 并在其下添加程序集的名称<behaviorExtensions>应如下所示:

<add name="RoutingServiceBehavior" type="Services.RoutingServiceBehavior.RoutingServiceBehaviorElement, Services.RoutingServiceBehavior, Version=1.0.0.0, Culture=neutral" />

7) 在你的 wcf 服务下添加你的服务行为的名称 <serviceDebug>

<RoutingServiceBehavior/>

8) 确保程序集 dll 包含在您的 WCF 服务中。

于 2013-06-13T13:52:54.470 回答