rebus-org / Rebus

:bus: Simple and lean service bus implementation for .NET
https://mookid.dk/category/rebus
Other
2.26k stars 355 forks source link

Not able to run program using Rebus InMemory transport #837

Closed SuheylZ closed 4 years ago

SuheylZ commented 4 years ago

I have made a very simple program to use Rebus but I'm unable to get it running as it always crashes. here is my program.

using System;
using System.Threading.Tasks;
using Rebus.Config;
using Rebus.Handlers;
using Rebus.Routing.TypeBased;
using Rebus.Transport.InMem;

namespace RebusLab
{
    class Program
    {
        private const string _queueName = "myqueue";

        static async Task Main(string[] args)
        {

            var activator = new Rebus.Activation.BuiltinHandlerActivator();

            var bus = Configure.With(activator)
                .Logging(l => l.None())
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), _queueName))
                .Routing(r=> r.TypeBased().Map<XMEssageHandler>(_queueName))
                .Start();

            await bus.Send(new XMEssage(23, "Hello World"));

            Console.ReadKey();
       }
    }

    public class XMEssage
    {
        public int Id { get;   }
        public string Name { get;   }

        public XMEssage(int id, string name)
        {
            Id = id;
            Name = name;
        }
    }

    public class XMEssageHandler : Rebus.Handlers.IHandleMessages<XMEssage>
    {
        public async Task Handle(XMEssage message)
        {
            Console.WriteLine($"{message.Id}=>{message.Name}");
            await Task.CompletedTask;
        }
    }
}
mookid8000 commented 4 years ago

The line

.Routing(r=> r.TypeBased().Map<XMEssageHandler>(_queueName))

doesn't make sense 🙂

If you change it to

.Routing(r=> r.TypeBased().Map<XMEssage>(_queueName))

then your program should work.

What you're telling Rebus in the line above could be paraphrased like this:

Yo Rebus, when I tell you to send a message of type XMEssage, send it to "myqueue"

SuheylZ commented 4 years ago

so how does it know that there is a handler without registering?

mookid8000 commented 4 years ago

oh, sorry, I missed that 🙂 the normal way would be to register it in your IoC container, but the "IoC container" in your case is the built-in handler activator, so you register it like this:

activator.Register(() => new XMEssageHandler());