nservicebusnservicebus-distributor

Add dynamic addresses in gateway NserviceBus


I am working on sending message to distributed systems. Hence I prefer to use Gateway. The problem is I am getting Sitekeys,addresses and channelType information dynamically. Nservicebus checks sitekeys and corresponding address in app.config. But there is nothing in my app.config. I wanted to modify app.config dynamically from code. Is this correct approach? Or there is any way to do this.

Below is the code.

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>

Code

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

Solution

  • You can do this dynamically during startup by creating a GatewayConfig object by inheriting from IProvideConfiguration<GatewayConfig> as shown in the following example.

    If there are new entries the bus instance needs to be rebuild.

    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"
                    }
                }
            };
        }
    }
    

    This example is based on the following sample from the documentation website: