Search code examples
.netbusrebus

Rebus and Handlers with Expensive Initialization/creation


As far as I know the usual behavior of buses including Rebus is creating a new handler for each message that arrives and match. This is fine in most cases but sometimes there will be expensive initialization handlers (will require to instantiate services proxies, connections, load objects on cache, etc.). There is a way to cache those handlers once they are created the first time, ideally one instance per worker, to avoid creating them over and over again?


Solution

  • If you have something that takes a long time to initialize, I suggest you use your IoC container to inject it, tweaking the lifestyle to your needs - with Castle Windsor, I usually configure expensive services to be singletons if they're reentrant, or tied to the current thread if they're not (which would end up creating a single instance per Rebus worker thread).

    Your options may vary depending on which IoC container you're using, but all containers should be able to do this.