Entity Framework with Nexus queues
If you're using Entity Framework you might want to sync your SaveChangesAsync() calls with calls to EnqueueAsync() on Nexus queues to ensure that they are committed together.
To achieve this you can install the CommerceMind.Nexus.EntityFramework package and initialize it like this in Program.cs:
builder.Services
.AddNexus()
.AddEntityFramework<MyDbContext>();
builder.Services.AddDbContext<MyDbContext>((serviceProvider, options) =>
{
options.UseNexus(serviceProvider);
});
This will install interceptors with Entity Framework that instead of sending a Nexus message directly to the database will keep it in the background until you call context.SaveChangesAsync() and will then use the same database connection and transaction that EF uses for your other data.
Note that if there's any messages to save Nexus will create an explicit transaction if there isn't already one. Which means that your EF data will be saved in the same transaction as your Nexus messages.
Only works with EnqueueAsync()
Note that this sync with SaveChangesAsync() only works with IEnqueuer.EnqueueAsync() and not other Nexus services like IQueueItemUpdater.
If you need that you can always create an explicit transaction yourself and use DbConnectionScope to make sure that any Nexus operations that happen in that scope use your explicit transaction.