在网关 NserviceBus 中添加动态地址

Add dynamic addresses in gateway NserviceBus

我正在致力于向分布式系统发送消息。因此我更喜欢使用网关。问题是我正在动态获取 Sitekeys、地址和 channelType 信息。 Nservicebus 检查 app.config 中的 sitekeys 和相应的地址。但是我的app.config里面什么都没有。我想从代码中动态修改 app.config。这是正确的方法吗?或者有什么方法可以做到这一点。

下面是代码。

App.config

<GatewayConfig>
    <Sites>
      <Site Key="RemoteSite" Address="http://localhost:25899/RemoteSite/" ChannelType="Http" />
    </Sites>
    <Channels>
      <Channel Address="http://localhost:25899/Headquarters/" ChannelType="Http" />
    </Channels>
  </GatewayConfig>

代码

          string[] siteKeys =
            {
                "RemoteSite"
            };
            PriceUpdated priceUpdated = new PriceUpdated
            {
                ProductId = 2,
                NewPrice = 100.0,
                ValidFrom = DateTime.Today,
            };
            bus.SendToSites(siteKeys, priceUpdated);

很遗憾,您无法在运行时更改 app.config 设置。我相信原因是 nservicebus 需要在端点启动之前对远程站点进行一些初始化。

您可以在启动期间通过继承 IProvideConfiguration<GatewayConfig> 创建一个 GatewayConfig 对象来动态执行此操作,如下例所示。

如果有新条目,则需要重建总线实例。

public class GatewayConfigConfigurationProvider : IProvideConfiguration<GatewayConfig>
{

    public GatewayConfig GetConfiguration()
    {
        return new GatewayConfig
        {
            Channels =
            {
                new ChannelConfig
                {
                    Address = "http://localhost:25899/Headquarters/",
                    ChannelType = "Http"
                }
            },
            Sites =
            {
                new SiteConfig
                {
                    Address = "http://localhost:25899/RemoteSite/",
                    ChannelType = "Http",
                    Key = "RemoteSite"
                }
            }
        };
    }
}

此示例基于文档网站中的以下示例: