我一直在关注 MSDN 上的 WCF 路由服务教程:
在尝试将控制台示例转换为 IIS 托管原型时经历了很多痛苦之后,我现在有了一个 WCF 路由服务,它按照教程每 5 秒更新一次其配置。
我现在需要从网页触发此更新,而不是定时器每 5 秒自动更新一次,但找不到任何有关如何执行此操作的示例。类似于管理屏幕的东西,它处理存储在数据库中的端点的 CRUD 操作。如果用户对配置进行更改,路由服务将需要动态更新其配置。
显然,您可以使用 UDP 公告和发现服务执行类似的操作,但我不希望触发从另一个应用程序调用的更新的简单端点就足够了。
如何获取对路由服务的引用UpdateBehavior
以便手动调用该UpdateRules
方法?
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Routing;
using System.Threading;
namespace ErpRoutingService
{
public class UpdateBehavior : BehaviorExtensionElement, IServiceBehavior
{
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
RulesUpdateExtension rulesUpdateExtension = new RulesUpdateExtension();
serviceHostBase.Extensions.Add(rulesUpdateExtension);
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
class RulesUpdateExtension : IExtension<ServiceHostBase>, IDisposable
{
bool primary = false;
ServiceHostBase owner;
Timer timer;
void IExtension<ServiceHostBase>.Attach(ServiceHostBase owner)
{
this.owner = owner;
//Call immediately, then every 5 seconds after that.
this.timer = new Timer(this.UpdateRules, this, TimeSpan.Zero, TimeSpan.FromSeconds(5));
}
void IExtension<ServiceHostBase>.Detach(ServiceHostBase owner)
{
this.Dispose();
}
public void Dispose()
{
if (this.timer != null)
{
this.timer.Dispose();
this.timer = null;
}
}
void UpdateRules(object state)
{
//Updating Routing Configuration
RoutingConfiguration rc = new RoutingConfiguration();
var inspector = new ErpMessageInspectorBehavior();
if (this.primary)
{
ServiceEndpoint endPoint101 = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IRequestReplyRouter)),
new BasicHttpBinding(),
new EndpointAddress("http://meldev:62395/ErpIntegrationService.svc"));
endPoint101.EndpointBehaviors.Add(inspector);
rc.FilterTable.Add(new MatchAllMessageFilter(), new List<ServiceEndpoint> { endPoint101 });
}
else
{
ServiceEndpoint endPoint102 = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IRequestReplyRouter)),
new BasicHttpBinding(),
new EndpointAddress("http://meldev:62396/ErpIntegrationService.svc"));
endPoint102.EndpointBehaviors.Add(inspector);
rc.FilterTable.Add(new MatchAllMessageFilter(), new List<ServiceEndpoint> { endPoint102 });
}
this.owner.Extensions.Find<RoutingExtension>().ApplyConfiguration(rc);
this.primary = !this.primary;
}
}
public override Type BehaviorType
{
get { return typeof(UpdateBehavior); }
}
protected override object CreateBehavior()
{
return new UpdateBehavior();
}
}
}