0

I'm using nServiceBus 5 and have created a number of host endpoints, two of which listen for database changes. (The specifics of how to do this can be found here). The intention is to have a service running in the background which publishes an event message using the Bus when notified to do so by the database listener.

The code which creates the database listener object and handles events is in the Start method, implemented as part of IWantToRunWhenBusStartsAndStops.

So - Is putting the code here likely to cause problems later on, for example if an exception is thrown (yes, I do have try/catch blocks, but I removed them from the sample code for clarity)? What happens when the Start method finishes executing?

Would I be better off with a constructor on my RequestNewQuoteSender class to instantiate the database listener as a class property and not use the Start method at all?

namespace MySample.QuoteRequest
{
    public partial class RequestNewQuoteSender : IWantToRunWhenBusStartsAndStops
    {
        public void Start() 
        { 
            var changeListener = new DatabaseChangeListener(_ConnectionString);

            // Assign the code within the braces to the DBListener's onChange event
            changeListener.OnChange += () =>
            {
                    // code to handle database change event

                    changeListener.Start(_SQLStatement);

            };

            // Now everything has been set up.... start it running.
            changeListener.Start(_SQLStatement);
        }

        public void Stop() { LogInfo("Service Bus has stopped"); }
    }
}
Community
  • 1
  • 1
Justin
  • 501
  • 5
  • 13

1 Answers1

1

Your code seems fine to me. Just a few small things:

  • Make changeListener a class field, so that it won't be GC (not 100% sure if it would be but just to make sure);
  • Unsubscribe from OnChange on the Stop() method;
  • You may also want to have a "lock" around changeListener.Start(_SQLStatement); and the Stop so that there are no racing conditions (I leave that one up to you to figure out if you need it or not);

Does this make sense ?

John Simons
  • 4,288
  • 23
  • 41
  • please can you elaborate on what you mean by 'have a "lock" around'. I understand what is meant by a race condition, and the other two points are also clear. – Justin Mar 03 '15 at 08:17
  • The "lock" is to ensure that you wait on the `Stop()` till the `OnChange` event completes executing. You may need to use a semaphore or something like it. – John Simons Mar 04 '15 at 07:22