This post details the steps that you need to take to configure a self hosted publisher and subscriber. With the Publisher Subscriber model in NService Bus multiple clients (subscribers) can subscribe to particular messages from a publisher. The Publisher will manage the subscriptions and Publish any messages to the Bus which will be distributed to all the subscribers.
Configuring The Subscriber
1) Reference NServiceBus.dll & NServiceBus.Core.dll. I’m using StructureMap as my IOC container so I have also referenced the NServiceBus.ObjectBuilder.StructureMap.dll as well.
2) In your Bootstrapper you need to configure NServiceBus
Configure .With() .StructureMapBuilder() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .UnicastBus() .ImpersonateSender(false) .LoadMessageHandlers() .CreateBus() .Start();
3) In the Application Config add the following
4) Now define the Subscribers’ Input Queue (where the subscribed to messages are sent to) and the Error Queue – where undelivered messages are put if there is an exception delivering the message in the config file
5) Now define the endpoint of the publisher that you wish to subscribe to messages from. This is a mapping between a message type and a particular publisher. You can either subscribe to all messages from an assembly or specify the type explicitly. In the example below I have specified that we wish to subscribe to every message in the Messages.dll that might be published.
Configuring The Publisher
6) Repeat steps 1) & 3) for the Server
7) Configure NServiceBus to run as a Publisher
Configure .With() .StructureMapBuilder() .MsmqSubscriptionStorage() .XmlSerializer() .MsmqTransport() .IsTransactional(true) .PurgeOnStartup(false) .UnicastBus() .ImpersonateSender(false) .CreateBus() .Start();
8 ) Now define the Publishers’ Input Queue (where subscription requests are sent to) and the Error Queue – where undelivered messages are put if there is an exception delivering the message in the config file
9) When you run up the applications NServiceBus will create the relevant queues for you. But be careful make sure you start up the Publisher first otherwise the subscriber will throw an exception as there is no queue for it to put a subscription on.
The important thing to note with the Publisher is that we have configured it with the use MsmqSubscriptionStorage() line. NServiceBus will create an additional queue called nservicebus_subscriptions and will store each subscription as an individual message on that queue. It is possible to use NHibernate to manage your subscriptions in a database if that is required.
Pubishing a Message
Simply call the Publish method on the instance of you Bus
The documentation at the NServiceBus web site has more detailed information on this.