Search code examples
msmqmasstransit

MassTransit Send only


I am implementing a Service Bus and having a look at MassTransit. My pattern is not Publish/Subscribe but Sender/Receiver where the Receiver can be offline and came back online later. Right now I am starting to write my tests to verify that MassTransit succesfully deliver the message using the following code:

bus = ServiceBusFactory.New(sbc =>
{
    sbc.UseMsmq(
        cfg =>
        {
            cfg.Configurator.UseJsonSerializer();
            cfg.Configurator.ReceiveFrom("msmq://localhost/my_queue");
            cfg.VerifyMsmqConfiguration();
        });
});

Then I grab the bus and publish a message like this:

bus.Publish<TMessage>(message);

As I can notice from MSMQ, two queues are created and the message is sent cause Mass Transit does not raise any error but I cannot find any message in the queue container. enter image description here

What am I doing wrong?

Update Reading the Mass Transit newsgroup I found out that in a scenario of Sender/Receiver where the receiver can come online at any time later, the message can be Send using this code:

bus.GetEndpoint(new Uri("msmq://localhost/my_queue")).Send<TMessage>(message);

Again in my scenario I am not writing a Publisher/Subscriber but a Sender/Receiver.


Solution

  • First, to send, you can use a simple EndpointCacheFactory instead of a ServiceBusFactory...

    var cache = EndpointCacheFactory.New(x => x.UseMsmq());
    

    From the cache, you can retrieve an endpoint by address:

    var endpoint = cache.GetEndpoint("msmq://localhost/queue_name");
    

    Then, you can use the endpoint to send a message:

    endpoint.Send(new MyMessage());
    

    To receive, you would create a bus instance as you specified above:

    var bus = ServiceBusFactory.New(x =>
    {
        x.UseMsmq();
        x.ReceiveFrom("msmq://localhost/queue_name");
    
        x.Subscribe(s => s.Handler<MyMessage>(x => {});
    });
    

    Once your receiver process is complete, call Dispose on the IServiceBus instance. Once your publisher is shutting down, call Dispose on the IEndpointCache instance.

    Do not dispose of the individual endpoints (IEndpoint) instances, the cache keeps them available for later use until it is disposed.