Wednesday, April 6, 2011

NServiceBus Customization Part 2: IWantToRunAtStartup

When NSB starts up it will look for all implementors of the interface IWantToRunAtStartup and call their Run() methods.  When NSB spins down it will also call the Stop() method of the same interface.  This gives us a good place to run expensive one time initialization code or to tweak out the bus prior to getting going.  A common usage of this interface is for the manual subscription to specific message types:
public IBus Bus { get; set; }

        #region IWantToRunAtStartup Members

        public void Run()
        {
            this.Bus.Subscribe<IProductUpdatedEvent>();
            this.Bus.Subscribe<IProductCreatedEvent>();
        }

        public void Stop()
        {
            this.Bus.Unsubscribe<IProductUpdatedEvent>();
            this.Bus.Unsubscribe<IProductCreatedEvent>();
        }

        #endregion
One thing that I would caution against doing in the Run() method is not exiting the method. I've seen cases where someone will go into an infinite loop and never exit Run(). Typically this is done to perform a task on a given interval. There are much better ways to do this, mostly commonly you can put a Timer into the container and wire into its events. If you never leave the Run() method, the Bus doesn't ever really startup and you will get some odd results.

2 comments:

  1. I have my service that implements IWantToRunAtStartup triggering twice.

    That ever happen? Or how does it get into a state that it triggers twice?

    -

    Joey

    ReplyDelete
  2. only if you implemented it twice. How are you hosting it?

    ReplyDelete