public async Task CanForwardToMultipleRecipients()
        {
            var network   = new InMemNetwork();
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            var recipients = new[] { "recipient-A", "recipient-B" }.ToList();

            recipients.ForEach(network.CreateQueue);

            Configure.With(activator)
            .Transport(t => t.UseInMemoryTransport(network, "forwarder"))
            .Routing(t =>
            {
                t.AddTransportMessageForwarder(async transportMessage => ForwardAction.ForwardTo(recipients));
            })
            .Start();

            await activator.Bus.SendLocal("HEJ MED DIG!!!");

            var transportMessages = await Task.WhenAll(recipients.Select(async queue =>
            {
                var message = await network.WaitForNextMessageFrom(queue);

                return(message);
            }));

            Assert.That(transportMessages.Length, Is.EqualTo(2));
        }
        static IBus GetFailingBus(BuiltinHandlerActivator activator, InMemNetwork network, string recipientQueueName, ErrorBehavior errorBehavior)
        {
            var deliveryAttempts = 0;

            var bus = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(network, "forwarder"))
                      .Routing(t =>
            {
                t.AddTransportMessageForwarder(async transportMessage =>
                {
                    deliveryAttempts++;

                    if (deliveryAttempts < 10)
                    {
                        throw new RebusApplicationException("fake an error");
                    }

                    return(ForwardAction.ForwardTo(recipientQueueName));
                }, errorBehavior);
            })
                      .Options(o =>
            {
                o.SetNumberOfWorkers(1);
                o.SetMaxParallelism(1);
            })
                      .Start();

            return(bus);
        }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var handlerActivator = new DependencyInjectionHandlerActivator(_serviceProvider);
        var configurer       = Configure.With(handlerActivator);

        configurer
        .Serialization(serializer => serializer.UseNewtonsoftJson(DefaultContentSerializer.CreateDefaultJsonSerializationSettings()))
        .Transport(transport => transport.UseAzureServiceBus(_configuration.GetConnectionString("AzureServiceBus"), "error"))
        .Routing(r =>
        {
            r.AddTransportMessageForwarder(transportMessage =>
            {
                var returnAddress = transportMessage.Headers[Headers.SourceQueue];

                if (returnAddress.Contains("workflow-management-events"))
                {
                    return(Task.FromResult(ForwardAction.Ignore()));
                }

                return(Task.FromResult(ForwardAction.ForwardTo(returnAddress)));
            });
        });

        var bus = configurer.Start();

        return(Task.CompletedTask);
    }
        public async Task CanDistributeWork(int numberOfMessages)
        {
            var transportConfigurer = GetTransportConfigurer();

            var workers = new[] { "worker1", "worker2", "worker3", "worker4" }
            .Select(TestConfig.GetName)
            .ToArray();

            var distributorQueueName = TestConfig.GetName("distributor");

            workers.ForEach(name =>
            {
                StartWorker(name, transportConfigurer);
            });

            var distributor = Configure.With(Using(new BuiltinHandlerActivator()))
                              .Logging(l => l.Console(LogLevel.Info))
                              .Transport(t =>
            {
                transportConfigurer(t, distributorQueueName);
            })
                              .Routing(r =>
            {
                var nextDestinationIndex = 0;

                r.AddTransportMessageForwarder(async transportMessage =>
                {
                    var headers = transportMessage.Headers;

                    if (headers.ContainsKey(SpecialHeaderKey))
                    {
                        var index = Interlocked.Increment(ref nextDestinationIndex) % workers.Length;

                        return(ForwardAction.ForwardTo(workers[index]));
                    }

                    return(ForwardAction.None);
                });
            })
                              .Options(o =>
            {
                o.LogPipeline(verbose: true);
            })
                              .Start();

            await Task.WhenAll(
                Enumerable.Range(0, numberOfMessages)
                .Select(id => new Work {
                WorkId = id
            })
                .Select(work => distributor.SendLocal(work, _forwardHeaders))
                );

            await _doneWork.WaitUntil(w => w.Count == numberOfMessages, timeoutSeconds : 20);

            var workByWorker = _doneWork.GroupBy(w => w.Worker).ToList();

            Console.WriteLine(@"Done work:

{0}

", string.Join(Environment.NewLine, workByWorker.Select(g => $"    {g.Key}: {g.Count()}")));

            Assert.That(workByWorker.Count, Is.EqualTo(workers.Length), "Expected that all workers got to do some work!");
        }