Bounded contexts and endpoints

Should multiple bounded contexts within an endpoint be avoided? We currently have some endpoints with multiple domain models, where some models are overlapping (mapped to the same database tables). For example, lets say we have declared a domain model consisting of “Order” and “OrderLine” in a namespace A. There is a one to many relationship between “Order” and “OrderLine”. In another namespace B we have declared another domain model, also consisting of “Order” and “OrderLine”. Using NHibernate Persistence, this is working fine when the NServiceBus’s NHibernate configuration does not include the mappings for these models. Access to A or B’s models are made via a separate ISession derived from a separate ISessionFactory which is injected in handlers where needed. Moving to enabling outbox in the endpoint, we want to access our models from the session instance on IMessageHandlerContext’s SyncronizedStorageSession instead. So we add our models to the NServiceBus’s NHibernate configuration. To our surprise this is then generating an exception in NServiceBus during startup/install if and only if the endpoint contains at least one saga.

Welcome to the Particular discussion group, @eriksy.

Let me try to address the two questions in your post starting from the bottom:

The synchronized storage session is available only when using sagas or the outbox, it’s meant to allow your code to participate in the same persistence transaction as the two mentioned features without the need of escalating to a distributed transaction. If those features are not enabled in the endpoint you can simply use the NHibernate session directly e.g., by injecting a dependency on the session factory.

That said, I’m not sure I understand precisely when the exception occurs. Can you also, please, post the exception details?

No, I’d say no. At the endpoint level handlers and sagas are the unit of isolation. So unless the same model is used by different sagas/handlers I would not be concerned by having multiple bounded contexts in the same endpoint.

By what you’re describing, though, it seems to me you’re creating coupling at the database level by having different models used by different handlers/sagas mapped to the same tables.

Hi Mauro and thanks for your feedback!

I ended up contacting support on the matter. It got registered as a bug:

In short, you cannot use NHibernate Persistence and add class mappings where some models are mapped to the same tables, if and only if the endpoint contains one or more Sagas. Sure, this means coupling between bounded contexts (or domain models if you will) at the database level, but NServiceBus should not guard against this perhaps, at least not unintentionally.

Ah, yeah. That makes a lot of sense. The persister should not make that assumption and cause bugs like that.