From f6e0d291339c792d763343cc57ae3a6b5396ebaa Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:00:55 +0000 Subject: [PATCH 01/13] [Mocha] Fix UseTransaction() opening its transaction on the DbContext registered last UseTransaction() looked up the DbContext type in a bus feature that every AddEntityFramework() call overwrote. With two contexts, the consumer transaction was opened on the context registered last, also when UseTransaction() was configured on the first. The middleware now gets the context type of the builder it is configured on. The builder extensions, the execution strategy and the transaction middleware move from MessageBusHostBuilderExtensions.cs into files of their own. --- ...ntityFrameworkConsumerExecutionStrategy.cs | 34 +++++ .../EntityFrameworkCoreBuilderExtensions.cs | 38 ++++++ ...tyFrameworkTransactionConsumeMiddleware.cs | 35 ++++++ .../MessageBusHostBuilderExtensions.cs | 119 ------------------ 4 files changed, 107 insertions(+), 119 deletions(-) create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs new file mode 100644 index 00000000000..aba6de9266a --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkConsumerExecutionStrategy.cs @@ -0,0 +1,34 @@ +using System.Runtime.ExceptionServices; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal sealed class EntityFrameworkConsumerExecutionStrategy(Type contextType) : IConsumerExecutionStrategy +{ + public async ValueTask ExecuteAsync(IConsumeContext context, Func executeAttempt) + { + await using var scope = context.Services.CreateAsyncScope(); + var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); + var strategy = dbContext.Database.CreateExecutionStrategy(); + + if (!strategy.RetriesOnFailure) + { + await executeAttempt(context.CancellationToken); + return; + } + + try + { + await strategy.ExecuteAsync( + executeAttemptToken => executeAttempt(executeAttemptToken).AsTask(), + context.CancellationToken); + } + catch (RetryLimitExceededException exception) when (exception.InnerException is not null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + throw; + } + } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs new file mode 100644 index 00000000000..8330e04080f --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCoreBuilderExtensions.cs @@ -0,0 +1,38 @@ +namespace Mocha.EntityFrameworkCore; + +/// +/// Configures Entity Framework Core resilience and transaction middleware. +/// +public static class EntityFrameworkCoreBuilderExtensions +{ + /// + /// Runs consumers with the DbContext execution strategy. + /// + /// The Entity Framework Core builder to configure. + /// The same instance for chaining. + public static IEntityFrameworkCoreBuilder UseResilience(this IEntityFrameworkCoreBuilder builder) + { + builder.HostBuilder.ConfigureMessageBus(x => + x.ConfigureFeature(f => + f.Set(new ConsumerExecutionStrategyFeature + { + Strategy = new EntityFrameworkConsumerExecutionStrategy(builder.ContextType) + }))); + + return builder; + } + + /// + /// Wraps each consumer invocation in a database transaction, committing on success + /// and rolling back on failure. + /// + /// The Entity Framework Core builder to configure. + /// The same instance for chaining. + public static IEntityFrameworkCoreBuilder UseTransaction(this IEntityFrameworkCoreBuilder builder) + { + builder.HostBuilder.ConfigureMessageBus(x => + x.UseConsume(EntityFrameworkTransactionConsumeMiddleware.Create(builder.ContextType)) + ); + return builder; + } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs new file mode 100644 index 00000000000..5696ff39710 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkTransactionConsumeMiddleware.cs @@ -0,0 +1,35 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal sealed class EntityFrameworkTransactionConsumeMiddleware(Type contextType) +{ + public async ValueTask InvokeAsync(IConsumeContext context, ConsumerDelegate next) + { + var dbContext = (DbContext)context.Services.GetRequiredService(contextType); + + await using var transaction = await dbContext.Database.BeginTransactionAsync(context.CancellationToken); + + try + { + await next(context); + + await transaction.CommitAsync(context.CancellationToken); + } + catch (Exception) + { + await transaction.RollbackAsync(context.CancellationToken); + throw; + } + } + + public static ConsumerMiddlewareConfiguration Create(Type contextType) + => new( + (_, next) => + { + var middleware = new EntityFrameworkTransactionConsumeMiddleware(contextType); + return ctx => middleware.InvokeAsync(ctx, next); + }, + "EntityFrameworkTransaction"); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index a70dacc3836..5d93fce8b5f 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -1,8 +1,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; -using System.Runtime.ExceptionServices; namespace Mocha.EntityFrameworkCore; @@ -44,123 +42,6 @@ public static IMessageBusHostBuilder AddEntityFramework( MessagingDbContextOptionsConfiguration >(); - builder.ConfigureMessageBus(x => - x.ConfigureFeature(f => f.Set(new EntityFrameworkConfigurationFeature { ContextType = typeof(TContext) })) - ); - return builder; } } - -/// -/// Provides extension methods on for configuring -/// resilience and transaction middleware for Entity Framework Core consumers. -/// -public static class EntityFrameworkCoreBuilderExtensions -{ - /// - /// Wraps consumer execution with the DbContext execution strategy, enabling automatic retry - /// for transient database failures such as connection drops or deadlocks. - /// - /// The Entity Framework Core builder to configure. - /// The same instance for chaining. - public static IEntityFrameworkCoreBuilder UseResilience(this IEntityFrameworkCoreBuilder builder) - { - builder.HostBuilder.ConfigureMessageBus(x => - x.ConfigureFeature(f => - f.Set(new ConsumerExecutionStrategyFeature - { - Strategy = new EntityFrameworkConsumerExecutionStrategy(builder.ContextType) - }))); - - return builder; - } - - /// - /// Wraps each consumer invocation in a database transaction, committing on success - /// and rolling back on failure. - /// - /// The Entity Framework Core builder to configure. - /// The same instance for chaining. - public static IEntityFrameworkCoreBuilder UseTransaction(this IEntityFrameworkCoreBuilder builder) - { - builder.HostBuilder.ConfigureMessageBus(x => - x.UseConsume(EntityFrameworkTransactionConsumeMiddleware.Create()) - ); - return builder; - } -} - -internal sealed class EntityFrameworkConfigurationFeature -{ - public Type? ContextType { get; set; } -} - -internal sealed class EntityFrameworkConsumerExecutionStrategy(Type contextType) : IConsumerExecutionStrategy -{ - public async ValueTask ExecuteAsync(IConsumeContext context, Func executeAttempt) - { - await using var scope = context.Services.CreateAsyncScope(); - var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); - var strategy = dbContext.Database.CreateExecutionStrategy(); - - if (!strategy.RetriesOnFailure) - { - await executeAttempt(context.CancellationToken); - return; - } - - try - { - await strategy.ExecuteAsync( - executeAttemptToken => executeAttempt(executeAttemptToken).AsTask(), - context.CancellationToken); - } - catch (RetryLimitExceededException exception) when (exception.InnerException is not null) - { - ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); - throw; - } - } -} - -internal sealed class EntityFrameworkTransactionConsumeMiddleware(Type contextType) -{ - public async ValueTask InvokeAsync(IConsumeContext context, ConsumerDelegate next) - { - var dbContext = (DbContext)context.Services.GetRequiredService(contextType); - - await using var transaction = await dbContext.Database.BeginTransactionAsync(context.CancellationToken); - - try - { - await next(context); - - await transaction.CommitAsync(context.CancellationToken); - } - catch (Exception) - { - await transaction.RollbackAsync(context.CancellationToken); - throw; - } - } - - public static ConsumerMiddlewareConfiguration Create() - => new( - static (context, next) => - { - var contextType = - context - .Services.GetRequiredService() - .Get() - ?.ContextType - ?? throw new InvalidOperationException( - "No Entity Framework Core DbContext type has been configured. " - + "Call AddEntityFramework() on the message bus host builder " - + "before using UseTransaction()."); - - var middleware = new EntityFrameworkTransactionConsumeMiddleware(contextType); - return ctx => middleware.InvokeAsync(ctx, next); - }, - "EntityFrameworkTransaction"); -} From 6be30e7af4b510246105ccd4fb78703b3b5cd5cf Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:01:53 +0000 Subject: [PATCH 02/13] [Mocha] Share the EF Core internal service provider between hosts that use Mocha The messaging options extension captured the application service provider and made it part of EF Core's service provider cache key, and the outbox and scheduling interceptors were created with the signals of that provider. Every host in a process therefore built its own EF Core internal service provider and model. The extension now carries the outbox signal, the scheduler signal and the clock of its application, and the interceptors read them from the context they are called for, so contexts of several hosts share one internal provider and still signal their own application. ConfigureEntityFrameworkServices and MessagingDbContextOptions become internal, because the delegate can no longer capture application services. --- .../DbContextMessagingServicesExtensions.cs | 14 + .../DbContextOptionsBuilderExtensions.cs | 6 +- ...ameworkCorePersistenceBuilderExtensions.cs | 21 +- .../MessageBusHostBuilderExtensions.cs | 16 +- .../MessagingDbContextOptions.cs | 18 +- .../MessagingDbContextOptionsConfiguration.cs | 6 +- .../MessagingDbContextOptionsExtension.cs | 21 +- .../MessagingDbContextServices.cs | 32 ++ .../Outbox/OutboxDbTransactionInterceptor.cs | 9 +- ...ameworkCorePersistenceBuilderExtensions.cs | 12 +- .../Outbox/OutboxSaveChangesInterceptor.cs | 7 +- .../SchedulingDbTransactionInterceptor.cs | 13 +- ...ameworkCorePersistenceBuilderExtensions.cs | 12 +- .../SchedulingSaveChangesInterceptor.cs | 12 +- .../TestDbContextOptionsBuilderExtensions.cs | 5 +- .../PostgresOutboxOptionsScopeTests.cs | 298 ++++++++++++++++++ .../Scheduling/SchedulingInterceptorTests.cs | 121 +++---- 17 files changed, 448 insertions(+), 175 deletions(-) create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs new file mode 100644 index 00000000000..fa3faca2344 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextMessagingServicesExtensions.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace Mocha.EntityFrameworkCore; + +internal static class DbContextMessagingServicesExtensions +{ + /// + /// Gets the application services carried by the messaging extension of the context options. + /// The context options must contain the messaging extension. + /// + public static MessagingDbContextServices GetMessagingServices(this DbContext context) + => context.GetService().FindExtension()!.Services; +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs index 9c1034617db..432185b3d14 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextOptionsBuilderExtensions.cs @@ -11,13 +11,15 @@ internal static class DbContextOptionsBuilderExtensions /// /// The DbContext options builder to extend. /// The messaging options carrying service configuration delegates. + /// The application services that the messaging interceptors and outbox use. /// The same instance for chaining. public static DbContextOptionsBuilder AddMessagingExtensions( this DbContextOptionsBuilder optionsBuilder, - MessagingDbContextOptions options) + MessagingDbContextOptions options, + MessagingDbContextServices services) { ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension( - new MessagingDbContextOptionsExtension(options)); + new MessagingDbContextOptionsExtension(options, services)); return optionsBuilder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs index ca9f98476ee..a637e53ff97 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/EntityFrameworkCorePersistenceBuilderExtensions.cs @@ -2,29 +2,20 @@ namespace Mocha.EntityFrameworkCore; -/// -/// Provides extension methods on for registering -/// additional services into the DbContext internal service provider. -/// -public static class EntityFrameworkCorePersistenceBuilderExtensions +internal static class EntityFrameworkCorePersistenceBuilderExtensions { /// - /// Registers a callback that configures services within the DbContext internal service provider, - /// allowing interceptors and other EF Core services to be injected alongside messaging infrastructure. + /// Registers services in the DbContext internal service provider. The delegate must not capture + /// application services. /// - /// The Entity Framework Core builder to configure. - /// - /// A delegate receiving the application and the DbContext - /// for registering additional services. - /// - /// The same instance for chaining. public static IEntityFrameworkCoreBuilder ConfigureEntityFrameworkServices( this IEntityFrameworkCoreBuilder builder, - Action configure) + Action configure) { builder.Services.Configure( builder.Name, - (options) => options.ConfigureServices.Add(configure)); + options => options.ConfigureServices.Add(configure)); + return builder; } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index 5d93fce8b5f..4e37adb402d 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -1,6 +1,9 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Mocha.Outbox; +using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; @@ -23,7 +26,7 @@ public static IMessageBusHostBuilder AddEntityFramework( Action configure) where TContext : DbContext { - var persistenceBuilder = new EntityFrameworkCoreBuilder + var efBuilder = new EntityFrameworkCoreBuilder { Services = builder.Services, HostBuilder = builder, @@ -31,11 +34,14 @@ public static IMessageBusHostBuilder AddEntityFramework( Name = typeof(TContext).FullName ?? typeof(TContext).Name }; - configure(persistenceBuilder); + configure(efBuilder); - builder - .Services.AddOptions(persistenceBuilder.Name) - .Configure((options, serviceProvider) => options.ServiceProvider = serviceProvider); + builder.Services.AddOptions(efBuilder.Name); + + builder.Services.TryAddSingleton(static services => new MessagingDbContextServices( + services.GetService(), + services.GetService(), + services.GetTimeProvider())); builder.Services.AddSingleton< IDbContextOptionsConfiguration, diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs index 1c90aa97599..c2acc42644b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptions.cs @@ -6,24 +6,10 @@ namespace Mocha.EntityFrameworkCore; /// Holds configuration state for a messaging-enabled DbContext, including service registration /// delegates that are applied when the DbContext internal service provider is built. /// -public class MessagingDbContextOptions +internal sealed class MessagingDbContextOptions { /// /// Gets the list of delegates that register services into the DbContext internal service provider. /// - public List> ConfigureServices { get; init; } = []; - - /// - /// Gets or sets the application-level service provider used to resolve dependencies during DbContext service configuration. - /// - /// - /// Thrown when accessed before the service provider has been configured. - /// - public IServiceProvider ServiceProvider - { - get => field ?? - throw new InvalidOperationException( - "ServiceProvider has not been configured. Ensure AddEntityFramework() has been called on the message bus host builder."); - set; - } + public List> ConfigureServices { get; init; } = []; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs index 7f2367f9133..aa1a17c1cb9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsConfiguration.cs @@ -4,7 +4,9 @@ namespace Mocha.EntityFrameworkCore; -internal class MessagingDbContextOptionsConfiguration(IOptionsMonitor monitor) +internal class MessagingDbContextOptionsConfiguration( + IOptionsMonitor monitor, + MessagingDbContextServices services) : IDbContextOptionsConfiguration where TContext : DbContext { /// @@ -25,6 +27,6 @@ public void Configure(IServiceProvider serviceProvider, DbContextOptionsBuilder throw new InvalidOperationException($"No options found for context {name}"); } - optionsBuilder.AddMessagingExtensions(options); + optionsBuilder.AddMessagingExtensions(options, services); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs index c383b9b220f..e2a6c86032e 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextOptionsExtension.cs @@ -9,10 +9,17 @@ namespace Mocha.EntityFrameworkCore; /// saga support) into the DbContext internal service provider during context construction. /// /// The messaging options containing service configuration delegates to apply. -internal class MessagingDbContextOptionsExtension(MessagingDbContextOptions options) : IDbContextOptionsExtension +/// The application services that the messaging interceptors and outbox of the context use. +internal class MessagingDbContextOptionsExtension( + MessagingDbContextOptions options, + MessagingDbContextServices services) : IDbContextOptionsExtension { - private readonly IServiceProvider _serviceProvider = options.ServiceProvider; - private readonly Action[] _configureServices = [.. options.ConfigureServices]; + private readonly Action[] _configureServices = [.. options.ConfigureServices]; + + /// + /// Gets the application services that the messaging interceptors and outbox of the context use. + /// + public MessagingDbContextServices Services { get; } = services; /// /// Gets the extension metadata used by EF Core for service provider caching and debug output. @@ -28,7 +35,7 @@ public void ApplyServices(IServiceCollection services) { foreach (var configureService in _configureServices) { - configureService(_serviceProvider, services); + configureService(services); } } @@ -58,7 +65,6 @@ public override int GetServiceProviderHashCode() var extension = (MessagingDbContextOptionsExtension)Extension; var hash = new HashCode(); - hash.Add(GetReferenceHashCode(extension._serviceProvider)); foreach (var configureService in extension._configureServices) { @@ -87,11 +93,6 @@ public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo var current = (MessagingDbContextOptionsExtension)Extension; var candidate = (MessagingDbContextOptionsExtension)otherInfo.Extension; - if (!ReferenceEquals(current._serviceProvider, candidate._serviceProvider)) - { - return false; - } - if (current._configureServices.Length != candidate._configureServices.Length) { return false; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs new file mode 100644 index 00000000000..b3796d5748d --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs @@ -0,0 +1,32 @@ +using Mocha.Outbox; +using Mocha.Scheduling; + +namespace Mocha.EntityFrameworkCore; + +/// +/// The application singletons that the messaging interceptors and the outbox of a DbContext use. +/// A service provider has one instance, which identifies the application of a context. +/// +/// The outbox signal of the application, or null when it has no outbox. +/// The scheduler signal of the application, or null when it has no scheduler. +/// The time provider of the application. +internal sealed class MessagingDbContextServices( + IOutboxSignal? outboxSignal, + ISchedulerSignal? schedulerSignal, + TimeProvider timeProvider) +{ + /// + /// Gets the outbox signal of the application, or null when the application has no outbox. + /// + public IOutboxSignal? OutboxSignal { get; } = outboxSignal; + + /// + /// Gets the scheduler signal of the application, or null when the application has no scheduler. + /// + public ISchedulerSignal? SchedulerSignal { get; } = schedulerSignal; + + /// + /// Gets the time provider of the application. + /// + public TimeProvider TimeProvider { get; } = timeProvider; +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs index 8113a5d8f62..c4f726b7e1e 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs @@ -1,16 +1,13 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Outbox; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core database transaction commit events to signal the outbox processor -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class OutboxDbTransactionInterceptor(IOutboxSignal signal) - : DbTransactionInterceptor - , ISingletonInterceptor +internal sealed class OutboxDbTransactionInterceptor : DbTransactionInterceptor { /// public override Task TransactionCommittedAsync( @@ -26,6 +23,6 @@ public override Task TransactionCommittedAsync( /// public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) { - signal.Set(); + eventData.Context?.GetMessagingServices().OutboxSignal?.Set(); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs index 23c8fbceccb..7ca644ec213 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -20,16 +20,12 @@ public static IEntityFrameworkCoreBuilder UseOutboxCore(this IEntityFrameworkCor { builder.HostBuilder.UseOutboxCore(); - builder.ConfigureEntityFrameworkServices((sp, services) => + builder.ConfigureEntityFrameworkServices(static services => { - var signal = sp.GetService(); - - if (signal is not null) - { - services.AddSingleton(new OutboxDbTransactionInterceptor(signal)); - services.AddSingleton(new OutboxSaveChangesInterceptor(signal)); - } + services.AddSingleton(); + services.AddSingleton(); }); + return builder; } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs index 2855bc19c3a..db4c1f1990b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs @@ -1,13 +1,12 @@ using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Outbox; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core save changes events to signal the outbox processor -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class OutboxSaveChangesInterceptor(IOutboxSignal signal) : SaveChangesInterceptor, ISingletonInterceptor +internal sealed class OutboxSaveChangesInterceptor : SaveChangesInterceptor { /// public override ValueTask SavedChangesAsync( @@ -28,7 +27,7 @@ public override int SavedChanges(SaveChangesCompletedEventData eventData, int re if (context.Database.CurrentTransaction is null) { - signal.SetAfterAmbientTransaction(); + context.GetMessagingServices().OutboxSignal?.SetAfterAmbientTransaction(); } return result; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs index 8f19bd8d792..8ffd5a17b74 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingDbTransactionInterceptor.cs @@ -1,16 +1,13 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core database transaction commit events to signal the scheduler -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class SchedulingDbTransactionInterceptor(ISchedulerSignal signal, TimeProvider timeProvider) - : DbTransactionInterceptor - , ISingletonInterceptor +internal sealed class SchedulingDbTransactionInterceptor : DbTransactionInterceptor { /// public override Task TransactionCommittedAsync( @@ -26,6 +23,10 @@ public override Task TransactionCommittedAsync( /// public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) { - signal.Notify(timeProvider.GetUtcNow()); + if (eventData.Context is { } context) + { + var services = context.GetMessagingServices(); + services.SchedulerSignal?.Notify(services.TimeProvider.GetUtcNow()); + } } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs index 6c834d3da07..ca05c7f7928 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -20,16 +20,10 @@ public static IEntityFrameworkCoreBuilder UseSchedulingCore(this IEntityFramewor { builder.HostBuilder.UseSchedulerCore(); - builder.ConfigureEntityFrameworkServices((sp, services) => + builder.ConfigureEntityFrameworkServices(static services => { - var signal = sp.GetService(); - - if (signal is not null) - { - var timeProvider = sp.GetService() ?? TimeProvider.System; - services.AddSingleton(new SchedulingDbTransactionInterceptor(signal, timeProvider)); - services.AddSingleton(new SchedulingSaveChangesInterceptor(signal, timeProvider)); - } + services.AddSingleton(); + services.AddSingleton(); }); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs index a682e56f22c..2ee5bb40493 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Scheduling/SchedulingSaveChangesInterceptor.cs @@ -1,17 +1,12 @@ using Microsoft.EntityFrameworkCore.Diagnostics; -using Mocha.Scheduling; namespace Mocha.EntityFrameworkCore; /// /// Intercepts Entity Framework Core save changes events to signal the scheduler -/// that messages are ready for dispatch. +/// of the application that created the context. /// -internal sealed class SchedulingSaveChangesInterceptor( - ISchedulerSignal signal, - TimeProvider timeProvider) - : SaveChangesInterceptor - , ISingletonInterceptor +internal sealed class SchedulingSaveChangesInterceptor : SaveChangesInterceptor { /// public override ValueTask SavedChangesAsync( @@ -32,7 +27,8 @@ public override int SavedChanges(SaveChangesCompletedEventData eventData, int re if (context.Database.CurrentTransaction is null) { - signal.Notify(timeProvider.GetUtcNow()); + var services = context.GetMessagingServices(); + services.SchedulerSignal?.Notify(services.TimeProvider.GetUtcNow()); } return result; diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs index 40a7679e432..e0d817ac17e 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/TestDbContextOptionsBuilderExtensions.cs @@ -5,9 +5,8 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; internal static class TestDbContextOptionsBuilderExtensions { - // Each test builds its own service provider, so EF accumulates more than twenty - // internal service providers across a run. Ignore the resulting warning instead of - // letting it throw. + // A test run builds more than twenty distinct EF Core configurations (data sources, interceptor + // instances), so EF's process-wide warning about many internal service providers is ignored. public static DbContextOptionsBuilder UseTestNpgsql( this DbContextOptionsBuilder optionsBuilder, string connectionString) diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs new file mode 100644 index 00000000000..a631dde8df2 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs @@ -0,0 +1,298 @@ +#if NET9_0_OR_GREATER +using System.Collections.Concurrent; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Time.Testing; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Outbox; +using Mocha.Scheduling; +using Mocha.Transport.InMemory; +using Npgsql; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxOptionsScopeTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly DateTimeOffset s_now = new(2026, 6, 1, 12, 0, 0, TimeSpan.Zero); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task SaveChangesAsync_Should_SignalOutbox_When_ScopedFactoryOptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedFactory, + signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + db.Orders.Add(new Order { Id = 2 }); + + // act + await db.SaveChangesAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal(2, signal.SetCallCount); + } + + [Fact] + public async Task SaveChangesAsync_Should_SignalOutbox_When_ConstructorOptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedOptions); + db.Orders.Add(new Order { Id = 2 }); + + // act + await db.SaveChangesAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal(2, signal.SetCallCount); + } + + [Fact] + public async Task CommitAsync_Should_SignalOutbox_When_OptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedFactory, + signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + db.Orders.Add(new Order { Id = 2 }); + await db.SaveChangesAsync(TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal(2, signal.SetCallCount); + } + + [Fact] + public async Task SaveChangesAsync_Should_NotifyScheduler_When_OptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new RecordingSchedulerSignal(); + await using var provider = await CreateSchedulingProviderAsync(connectionString, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + db.Orders.Add(new Order { Id = 2 }); + + // act + await db.SaveChangesAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal([s_now, s_now], signal.Notifications); + } + + [Fact] + public async Task CommitAsync_Should_NotifyScheduler_When_OptionsScopeIsDisposed() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + var signal = new RecordingSchedulerSignal(); + await using var provider = await CreateSchedulingProviderAsync(connectionString, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + db.Orders.Add(new Order { Id = 2 }); + await db.SaveChangesAsync(TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(2, await CountOrdersAsync(connectionString)); + Assert.Equal([s_now, s_now], signal.Notifications); + } + + [Fact] + public async Task SaveChangesAsync_Should_SignalOwnApplication_When_ApplicationsShareEntityFrameworkServices() + { + // arrange + var connectionString = await CreateDatabaseAsync(); + StubOutboxSignal[] signals = [new(), new(), new()]; + await using var first = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[0]); + await using var second = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[1]); + await using var third = await CreateOutboxProviderAsync( + connectionString, + ContextRegistration.ScopedOptions, + signals[2]); + ServiceProvider[] providers = [first, second, third]; + var modelSources = new HashSet(ReferenceEqualityComparer.Instance); + + // act + for (var i = 0; i < providers.Length; i++) + { + await using var scope = providers[i].CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Orders.Add(new Order { Id = i + 1 }); + await db.SaveChangesAsync(TestToken); + modelSources.Add(db.GetService()); + } + + // assert + Assert.Single(modelSources); + Assert.Equal([true, true, true], signals.Select(s => s.WasSet)); + } + + private async Task CreateDatabaseAsync() + { + var connectionString = await fixture.CreateDatabaseAsync(); + var options = new DbContextOptionsBuilder().UseTestNpgsql(connectionString).Options; + await using var db = new ScopeDbContext(options); + await db.Database.EnsureCreatedAsync(TestToken); + return connectionString; + } + + private static async Task CreateContextOutlivingScopeAsync( + IServiceProvider provider, + ContextRegistration registration) + { + await using var scope = provider.CreateAsyncScope(); + var db = registration == ContextRegistration.ScopedFactory + ? await scope.ServiceProvider + .GetRequiredService>() + .CreateDbContextAsync(TestToken) + : new ScopeDbContext(scope.ServiceProvider.GetRequiredService>()); + db.Orders.Add(new Order { Id = 1 }); + await db.SaveChangesAsync(TestToken); + return db; + } + + private static async Task CountOrdersAsync(string connectionString) + { + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(TestToken); + await using var command = connection.CreateCommand(); + command.CommandText = "SELECT COUNT(*) FROM orders"; + return (long)(await command.ExecuteScalarAsync(TestToken))!; + } + + private static Task CreateOutboxProviderAsync( + string connectionString, + ContextRegistration registration, + IOutboxSignal signal) + => CreateProviderAsync( + connectionString, + registration, + services => services.AddSingleton(signal), + static ef => ef.UsePostgresOutbox()); + + private static Task CreateSchedulingProviderAsync( + string connectionString, + ISchedulerSignal signal) + => CreateProviderAsync( + connectionString, + ContextRegistration.ScopedFactory, + services => + { + services.AddSingleton(signal); + services.AddSingleton(new FakeTimeProvider(s_now)); + }, + static ef => ef.UsePostgresScheduling()); + + private static async Task CreateProviderAsync( + string connectionString, + ContextRegistration registration, + Action configureServices, + Action configureEntityFramework) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + configureServices(services); + + if (registration == ContextRegistration.ScopedFactory) + { + services.AddDbContextFactory( + options => options.UseTestNpgsql(connectionString), + ServiceLifetime.Scoped); + } + else + { + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + } + + var builder = services.AddMessageBus(); + builder.AddEntityFramework(configureEntityFramework); + builder.AddEventHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + return provider; + } + + private enum ContextRegistration + { + ScopedFactory, + ScopedOptions + } + + public sealed class ScopeDbContext(DbContextOptions options) : DbContext(options) + { + public DbSet Orders => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.AddPostgresOutbox(); + modelBuilder.AddPostgresScheduledMessages(); + modelBuilder.Entity().ToTable("orders").Property(order => order.Id).ValueGeneratedNever(); + } + } + + public sealed class Order + { + public int Id { get; set; } + } + + public sealed record OrderPlaced(int OrderId); + + public sealed class MessageRecorder + { + public TaskCompletionSource Delivered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public sealed class OrderPlacedHandler(MessageRecorder recorder) : IEventHandler + { + public ValueTask HandleAsync(OrderPlaced message, CancellationToken cancellationToken) + { + recorder.Delivered.TrySetResult(message); + return default; + } + } + + private sealed class RecordingSchedulerSignal : ISchedulerSignal + { + public ConcurrentQueue Notifications { get; } = new(); + + public void Notify(DateTimeOffset scheduledTime) => Notifications.Enqueue(scheduledTime); + + public Task WaitUntilAsync(DateTimeOffset wakeTime, CancellationToken cancellationToken) + => Task.Delay(Timeout.Infinite, cancellationToken); + } +} +#endif diff --git a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs index 81a43729961..53f91e167dc 100644 --- a/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs +++ b/src/Mocha/test/Mocha.Tests/Scheduling/SchedulingInterceptorTests.cs @@ -1,14 +1,10 @@ using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.EntityFrameworkCore.Diagnostics.Internal; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Time.Testing; using Mocha.EntityFrameworkCore; using Mocha.Scheduling; -#pragma warning disable EF1001 // LoggingOptions is an internal EF Core API, used here only to construct event data for tests. - namespace Mocha.Tests.Scheduling; public sealed class SchedulingInterceptorTests : IDisposable @@ -16,6 +12,9 @@ public sealed class SchedulingInterceptorTests : IDisposable private static readonly DateTimeOffset s_baseTime = new(2026, 6, 1, 12, 0, 0, TimeSpan.Zero); + private static readonly SchedulingDbTransactionInterceptor s_transactionInterceptor = new(); + private static readonly SchedulingSaveChangesInterceptor s_saveChangesInterceptor = new(); + private readonly SqliteConnection _connection; public SchedulingInterceptorTests() @@ -28,12 +27,14 @@ public SchedulingInterceptorTests() public void TransactionCommitted_Should_NotifySignalWithExactTime_When_Called() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingDbTransactionInterceptor(signal, timeProvider); + using var services = CreateServices(signal); + using var scope = services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + using var transaction = dbContext.Database.BeginTransaction(); // act - interceptor.TransactionCommitted(null!, null!); + transaction.Commit(); // assert var notification = Assert.Single(signal.Notifications); @@ -44,12 +45,15 @@ public void TransactionCommitted_Should_NotifySignalWithExactTime_When_Called() public async Task TransactionCommittedAsync_Should_NotifySignalWithExactTime_When_Called() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingDbTransactionInterceptor(signal, timeProvider); + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await dbContext.Database.BeginTransactionAsync( + TestContext.Current.CancellationToken); // act - await interceptor.TransactionCommittedAsync(null!, null!, TestContext.Current.CancellationToken); + await transaction.CommitAsync(TestContext.Current.CancellationToken); // assert var notification = Assert.Single(signal.Notifications); @@ -57,18 +61,16 @@ public async Task TransactionCommittedAsync_Should_NotifySignalWithExactTime_Whe } [Fact] - public async Task SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() + public void SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); + using var services = CreateServices(signal); + using var scope = services.CreateScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); - await using var dbContext = CreateDbContext(); - var eventData = CreateSaveChangesEventData(dbContext); - - // act no transaction is open on the context - interceptor.SavedChanges(eventData, 1); + // act + dbContext.SaveChanges(); // assert var notification = Assert.Single(signal.Notifications); @@ -79,40 +81,17 @@ public async Task SavedChanges_Should_NotifySignal_When_NoAmbientTransaction() public async Task SavedChanges_Should_NotNotifySignal_When_AmbientTransactionExists() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - await using var dbContext = CreateDbContext(); - dbContext.Database.EnsureCreated(); - - // Begin a transaction so CurrentTransaction is non-null + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); await using var transaction = await dbContext.Database.BeginTransactionAsync( TestContext.Current.CancellationToken); - var eventData = CreateSaveChangesEventData(dbContext); // act - interceptor.SavedChanges(eventData, 1); - - // assert signal should NOT have been notified - Assert.Empty(signal.Notifications); - } + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); - [Fact] - public void SavedChanges_Should_ReturnResult_When_ContextIsNull() - { - // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); - var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - var eventData = CreateSaveChangesEventData(context: null); - - // act - var result = interceptor.SavedChanges(eventData, 42); - - // assert result passes through, no notification - Assert.Equal(42, result); + // assert Assert.Empty(signal.Notifications); } @@ -120,45 +99,32 @@ public void SavedChanges_Should_ReturnResult_When_ContextIsNull() public async Task SavedChangesAsync_Should_NotifySignal_When_NoAmbientTransaction() { // arrange - var timeProvider = new FakeTimeProvider(s_baseTime); var signal = new RecordingSchedulerSignal(); - var interceptor = new SchedulingSaveChangesInterceptor(signal, timeProvider); - - await using var dbContext = CreateDbContext(); - var eventData = CreateSaveChangesEventData(dbContext); + await using var services = CreateServices(signal); + await using var scope = services.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); // act - var result = await interceptor.SavedChangesAsync(eventData, 1, TestContext.Current.CancellationToken); + await dbContext.SaveChangesAsync(TestContext.Current.CancellationToken); // assert - Assert.Equal(1, result); var notification = Assert.Single(signal.Notifications); Assert.Equal(s_baseTime, notification); } - private TestDbContext CreateDbContext() + private ServiceProvider CreateServices(RecordingSchedulerSignal signal) { - var options = new DbContextOptionsBuilder() + var messagingServices = new MessagingDbContextServices( + outboxSignal: null, + signal, + new FakeTimeProvider(s_baseTime)); + var services = new ServiceCollection(); + services.AddDbContext(options => options .UseSqlite(_connection) - .Options; - - return new TestDbContext(options); - } + .AddMessagingExtensions(new MessagingDbContextOptions(), messagingServices) + .AddInterceptors(s_transactionInterceptor, s_saveChangesInterceptor)); - private static SaveChangesCompletedEventData CreateSaveChangesEventData(DbContext? context) - { - var loggingOptions = new LoggingOptions(); - var eventDefinition = new StubEventDefinition( - loggingOptions, - new EventId(1, "TestSaveChanges"), - LogLevel.Information, - "TestSaveChanges"); - - return new SaveChangesCompletedEventData( - eventDefinition, - static (_, _) => "test", - context!, - entitiesSavedCount: 0); + return services.BuildServiceProvider(); } public void Dispose() @@ -179,12 +145,5 @@ public Task WaitUntilAsync(DateTimeOffset wakeTime, CancellationToken cancellati => Task.CompletedTask; } - private sealed class StubEventDefinition( - ILoggingOptions loggingOptions, - EventId eventId, - LogLevel level, - string eventIdCode) - : EventDefinitionBase(loggingOptions, eventId, level, eventIdCode); - private sealed class TestDbContext(DbContextOptions options) : DbContext(options); } From e17c933e44faad0755b1b8443bc5e949b774475e Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:02:41 +0000 Subject: [PATCH 03/13] [Mocha] Fix the outbox processor never checking for messages it is not signaled about An idle outbox processor waited for its signal without a timeout. A row committed without a signal, for example in a transaction that is committed outside EF Core or by another process, stayed in the outbox until something else woke the processor. The processor now also wakes after PostgresOutboxOptions.PollingInterval, ten seconds by default, and an interval that is not positive is rejected. It logs that it is sleeping only when it waits for a message that is due before the next check. --- .../Outbox/OutboxProcessor.cs | 50 +++-- .../OutboxServiceCollectionExtensions.cs | 10 +- .../Outbox/PostgresOutboxOptions.cs | 6 + .../PostgresOutboxRelayClockTests.cs | 182 ++++++++++++++++++ .../PostgresOutboxSleepLogTests.cs | 143 ++++++++++++++ 5 files changed, 369 insertions(+), 22 deletions(-) create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs index 895578a88ed..515398e0490 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs @@ -20,6 +20,7 @@ public sealed class PostgresOutboxProcessor private readonly ObjectPool _contextPool; private readonly PostgresMessageOutboxOptions _options; private readonly TimeProvider _timeProvider; + private readonly TimeSpan _pollingInterval; /// /// Initializes a new instance of the class. @@ -42,13 +43,15 @@ public sealed class PostgresOutboxProcessor /// /// The outbox options containing the SQL queries and connection factory. /// + /// How long an idle worker waits before checking for messages to send. internal PostgresOutboxProcessor( ILogger logger, IServiceProvider services, IMessagingRuntime runtime, IMessagingPools pools, IOutboxSignal signal, - PostgresMessageOutboxOptions options) + PostgresMessageOutboxOptions options, + TimeSpan pollingInterval) { _logger = logger; _services = services; @@ -56,7 +59,8 @@ internal PostgresOutboxProcessor( _signal = signal; _contextPool = pools.DispatchContext; _options = options; - _timeProvider = services.GetService() ?? TimeProvider.System; + _timeProvider = services.GetTimeProvider(); + _pollingInterval = pollingInterval; } /// @@ -66,36 +70,40 @@ internal PostgresOutboxProcessor( /// A token that signals when the processor should stop. public async Task ProcessAsync(CancellationToken cancellationToken) { - while (!cancellationToken.IsCancellationRequested) + using var signalCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + try { - using var joinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var signaled = _signal.WaitAsync(signalCts.Token); - try + while (!cancellationToken.IsCancellationRequested) { - var signaled = _signal.WaitAsync(joinedCts.Token); - var nextPollingInterval = await ProcessPendingAsync(cancellationToken); + var delay = _pollingInterval; - if (nextPollingInterval is not null) + if (nextPollingInterval is { } interval && interval < _pollingInterval) { - _logger.OutboxProcessorSleeping(nextPollingInterval.Value); - - await Task.WhenAny(Task.Delay(nextPollingInterval.Value, cancellationToken), signaled); + delay = interval; + _logger.OutboxProcessorSleeping(delay); } - else + + using var delayCts = new CancellationTokenSource(); + await Task.WhenAny(Task.Delay(delay, delayCts.Token), signaled); + delayCts.TryCancel(); + + if (signaled.IsCompleted) { await signaled; + signaled = _signal.WaitAsync(signalCts.Token); } } - catch (OperationCanceledException) - { - joinedCts.TryCancel(); - } - catch - { - joinedCts.TryCancel(); - throw; - } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + finally + { + signalCts.TryCancel(); } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 1e16b12ac83..fc6458405fa 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -45,6 +45,12 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( var contextType = builder.ContextType; builder.Services.AddOptions(builder.Name).Configure(configure); + builder.Services.AddOptions(builder.Name) + .Validate( + options => options.PollingInterval > TimeSpan.Zero, + $"{nameof(PostgresOutboxOptions)}.{nameof(PostgresOutboxOptions.PollingInterval)} " + + "must be greater than zero."); + builder .Services.AddOptions(builder.Name) .Configure((options, sp) => @@ -74,13 +80,15 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); + var outboxOptions = sp.GetRequiredService>().Get(builder.Name); return new PostgresOutboxProcessor( sp.GetRequiredService>(), sp, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), - options); + options, + outboxOptions.PollingInterval); }); builder.Services.AddSingleton(); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs index cc70588790a..df8f1191414 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresOutboxOptions.cs @@ -5,6 +5,12 @@ namespace Mocha.Outbox; /// public sealed class PostgresOutboxOptions { + /// + /// Gets or sets how long an idle worker waits before checking the database for messages to send + /// when no notification arrives. The default is 10 seconds. + /// + public TimeSpan PollingInterval { get; set; } = TimeSpan.FromSeconds(10); + /// /// Gets or sets whether a publish or send through the outbox requires an active database or ambient /// transaction and throws an without one. The default is true. diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs new file mode 100644 index 00000000000..f356ebbef6e --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs @@ -0,0 +1,182 @@ +using System.Data; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxRelayClockTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + private static readonly DateTimeOffset s_now = new(2050, 1, 1, 12, 0, 0, TimeSpan.Zero); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_RetryFailedSend_When_RegisteredClockDoesNotAdvance() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var recorder = new DeliveryRecorder { FailFirstAttempt = true }; + // with an hour-long polling interval, only the wait until the failed row is due can retry it in time + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromHours(1), recorder); + await MessageRows.InsertOutboxAsync(connectionString, CreateEnvelope(provider), TestToken); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + var delivered = await recorder.Delivered.Task.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(2, recorder.Attempts); + Assert.Equal("pending", delivered.Value); + } + + [Fact] + public async Task ProcessAsync_Should_DeliverUnsignaledMessage_When_RegisteredClockDoesNotAdvance() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var recorder = new DeliveryRecorder(); + await using var provider = await CreateProviderAsync( + connectionString, TimeSpan.FromMilliseconds(100), recorder); + var firstPollEnded = ObserveFirstPoll(provider); + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + // the first poll ended with an empty outbox, so only a later poll can find the next row + await firstPollEnded.WaitAsync(s_timeout, TestToken); + + // act + await MessageRows.InsertOutboxAsync(connectionString, CreateEnvelope(provider), TestToken); + var delivered = await recorder.Delivered.Task.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(1, recorder.Attempts); + Assert.Equal("pending", delivered.Value); + } + + private static Task ObserveFirstPoll(ServiceProvider provider) + { + var firstPollEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var options = provider.GetRequiredService>() + .Get(typeof(TestDbContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed) + { + firstPollEnded.TrySetResult(); + } + }; + return connection; + }; + + return firstPollEnded.Task; + } + + private static MessageEnvelope CreateEnvelope(IServiceProvider provider) + { + var runtime = provider.GetRequiredService(); + var type = runtime.GetMessageType(typeof(ClockEvent)); + return new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = type.Identity, + ContentType = MessageContentType.Json.Value, + DestinationAddress = runtime.GetPublishEndpoint(type).Address.ToString(), + Body = JsonSerializer.SerializeToUtf8Bytes(new ClockEvent { Value = "pending" }) + }; + } + + private static async Task CreateProviderAsync( + string connectionString, + TimeSpan pollingInterval, + DeliveryRecorder recorder) + { + var services = new ServiceCollection(); + services.AddSingleton(new FakeTimeProvider(s_now)); + services.AddSingleton(); + services.AddSingleton(recorder); + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = pollingInterval)); + builder.AddEventHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(); + var runtime = (MessagingRuntime)provider.GetRequiredService(); + await runtime.StartAsync(TestToken); + var endpoint = runtime.GetPublishEndpoint(runtime.GetMessageType(typeof(ClockEvent))); + var recordingEndpoint = new RecordingDispatchEndpoint(endpoint, recorder); + recordingEndpoint.Initialize(runtime, new DispatchEndpointConfiguration { Name = endpoint.Name }); + recordingEndpoint.Complete(runtime); + runtime.Endpoints.Remove(endpoint); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + public sealed class ClockEvent + { + public required string Value { get; init; } + } + + public sealed class ClockEventHandler(DeliveryRecorder recorder) : IEventHandler + { + public ValueTask HandleAsync(ClockEvent message, CancellationToken cancellationToken) + { + recorder.Delivered.TrySetResult(message); + return default; + } + } + + public sealed class DeliveryRecorder + { + private int _attempts; + + public bool FailFirstAttempt { get; init; } + + public int Attempts => Volatile.Read(ref _attempts); + + public TaskCompletionSource Delivered { get; } = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public void RecordAttempt() + { + if (Interlocked.Increment(ref _attempts) == 1 && FailFirstAttempt) + { + throw new InvalidOperationException("The first send failed deliberately."); + } + } + } + + private sealed class RecordingDispatchEndpoint(DispatchEndpoint endpoint, DeliveryRecorder recorder) + : DispatchEndpoint(endpoint.Transport) + { + protected override void OnInitialize( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { + Address = endpoint.Address; + Destination = endpoint.Destination; + } + + protected override void OnComplete( + IMessagingConfigurationContext context, + DispatchEndpointConfiguration configuration) + { } + + protected override ValueTask DispatchAsync(IDispatchContext context) + { + recorder.RecordAttempt(); + return endpoint.DispatchInternalAsync(context); + } + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs new file mode 100644 index 00000000000..fe60873c429 --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs @@ -0,0 +1,143 @@ +using System.Collections.Concurrent; +using System.Data; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; +using Npgsql; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxSleepLogTests(PostgresFixture fixture) : IClassFixture +{ + private static readonly TimeSpan s_timeout = TimeSpan.FromSeconds(30); + + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task ProcessAsync_Should_NotLogSleep_When_NextMessageIsDueAfterPollingInterval() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var logger = new CapturingLogger(); + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromMilliseconds(50), logger); + await InsertMessageInRetryDelayAsync(connectionString, TimeSpan.FromHours(1)); + var thirdPollEnded = ObservePolls(provider, count: 3); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + await thirdPollEnded.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Empty(logger.Entries); + } + + [Fact] + public async Task ProcessAsync_Should_LogSleep_When_NextMessageIsDueBeforePollingInterval() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var logger = new CapturingLogger(); + await using var provider = await CreateProviderAsync(connectionString, TimeSpan.FromHours(1), logger); + await InsertMessageInRetryDelayAsync(connectionString, TimeSpan.FromMinutes(1)); + + // act + await using var host = await MessagingTestHost.StartAsync(provider, TestToken); + var entry = await logger.FirstEntry.WaitAsync(s_timeout, TestToken); + + // assert + Assert.Equal(LogLevel.Information, entry.Level); + Assert.Equal("OutboxProcessorSleeping", entry.EventId.Name); + } + + private static Task ObservePolls(ServiceProvider provider, int count) + { + var pollsEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var polls = 0; + var options = provider.GetRequiredService>() + .Get(typeof(TestDbContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed && Interlocked.Increment(ref polls) == count) + { + pollsEnded.TrySetResult(); + } + }; + return connection; + }; + + return pollsEnded.Task; + } + + private static async Task InsertMessageInRetryDelayAsync(string connectionString, TimeSpan dueIn) + { + var envelope = new MessageEnvelope { MessageId = Guid.NewGuid().ToString() }; + var id = await MessageRows.InsertOutboxAsync(connectionString, envelope, timesSent: 1, TestToken); + + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(TestToken); + await using var command = connection.CreateCommand(); + command.CommandText = """UPDATE "outbox_messages" SET "created_at" = NOW() + @dueIn WHERE "id" = @id;"""; + command.Parameters.AddWithValue("@dueIn", dueIn); + command.Parameters.AddWithValue("@id", id); + await command.ExecuteNonQueryAsync(TestToken); + } + + private static async Task CreateProviderAsync( + string connectionString, + TimeSpan pollingInterval, + CapturingLogger logger) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton>(logger); + services.AddSingleton(); + services.AddDbContext(options => options.UseTestNpgsql(connectionString)); + var builder = services.AddMessageBus(); + builder.AddEntityFramework( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = pollingInterval)); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + private sealed record LogEntry(LogLevel Level, EventId EventId, string Message); + + private sealed class CapturingLogger : ILogger + { + private readonly ConcurrentQueue _entries = new(); + private readonly TaskCompletionSource _firstEntry = + new(TaskCreationOptions.RunContinuationsAsynchronously); + + public IReadOnlyCollection Entries => _entries; + + public Task FirstEntry => _firstEntry.Task; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + var entry = new LogEntry(logLevel, eventId, formatter(state, exception)); + _entries.Enqueue(entry); + _firstEntry.TrySetResult(entry); + } + } +} From 9fb071b4ff3beadf4ccd6dd9404f962252861ff2 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:03:30 +0000 Subject: [PATCH 04/13] [Mocha] Fix the Postgres outbox running one processor when several DbContexts use it UsePostgresOutbox() registered the processor and its worker as plain singletons, so with two contexts the host ran only the processor of the context registered last and the rows of the other context were never sent. Each context now gets its own processor, registered as a keyed singleton with the context type as key, and its own worker. Calling UsePostgresOutbox() or UseOutboxCore() again for the same context registers nothing twice and still applies the configure delegate. IMessageBus publishes keep using the outbox of the first context, and the exception for a missing transaction now says so. --- .../OutboxServiceCollectionExtensions.cs | 39 ++- .../Outbox/PostgresMessageOutbox.cs | 18 +- .../Outbox/ThrowHelper.cs | 17 + .../MessageBusHostBuilderExtensions.cs | 4 +- .../Outbox/OutboxDbContextRegistration.cs | 3 + ...ameworkCorePersistenceBuilderExtensions.cs | 9 + .../OutboxServiceRegistrationTests.cs | 57 +++- .../PostgresMultipleContextOutboxTests.cs | 292 ++++++++++++++++++ .../PostgresOutboxDataSourceTests.cs | 5 +- ...PostgresOutboxRepeatedRegistrationTests.cs | 108 +++++++ .../PostgresOutboxRetryTests.cs | 4 +- .../PostgresOutboxTransactionTests.cs | 23 +- 12 files changed, 515 insertions(+), 64 deletions(-) create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs create mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index fc6458405fa..08b50d7431b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Mocha.EntityFrameworkCore; @@ -11,30 +12,23 @@ namespace Mocha.Outbox; /// -/// Provides extension methods on for registering -/// the Postgres outbox infrastructure including the outbox processor, worker, and message persistence. +/// Registers the Postgres outbox for an Entity Framework Core . /// public static class OutboxServiceCollectionExtensions { /// - /// Registers the full Postgres outbox pipeline: table info discovery from the EF Core model, - /// the , a hosted background worker, and a scoped - /// backed by direct Npgsql inserts. + /// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit. /// - /// - /// This method also calls - /// to register the EF Core interceptors that signal the processor on save and commit. - /// /// The Entity Framework Core builder to configure. /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UsePostgresOutbox(this IEntityFrameworkCoreBuilder builder) => builder.UsePostgresOutbox(static _ => { }); /// - /// Registers the full Postgres outbox pipeline with the specified . + /// Stores outgoing messages in the outbox table of the context and relays them to the transport after commit. /// /// The Entity Framework Core builder to configure. - /// A delegate that configures the . + /// Configures the . /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UsePostgresOutbox( this IEntityFrameworkCoreBuilder builder, @@ -42,9 +36,18 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { ArgumentNullException.ThrowIfNull(configure); - var contextType = builder.ContextType; + builder.UseOutboxCore(); builder.Services.AddOptions(builder.Name).Configure(configure); + var contextType = builder.ContextType; + + if (builder.Services.Any(descriptor => + descriptor.ServiceType == typeof(PostgresOutboxProcessor) + && Equals(descriptor.ServiceKey, contextType))) + { + return builder; + } + builder.Services.AddOptions(builder.Name) .Validate( options => options.PollingInterval > TimeSpan.Zero, @@ -76,7 +79,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( options.Queries = PostgresMessageOutboxQueries.From(tableInfo.Outbox); }); - builder.Services.AddSingleton(sp => + builder.Services.AddKeyedSingleton(contextType, (sp, _) => { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); @@ -91,15 +94,11 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( outboxOptions.PollingInterval); }); - builder.Services.AddSingleton(); - - builder.Services.AddHostedService(sp => sp.GetRequiredService()); + builder.Services.AddSingleton(sp => + new PostgresMessageBusOutboxWorker(sp.GetRequiredKeyedService(contextType))); builder.Services.TryAddScoped(sp => - PostgresMessageOutbox.Create(contextType, builder.Name, sp) - ); - - builder.UseOutboxCore(); + PostgresMessageOutbox.Create(contextType, builder.Name, sp)); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index 809c54c236b..c5ed0a39efa 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -13,14 +13,8 @@ namespace Mocha.Outbox; /// -/// Implements for Postgres by inserting serialized message envelopes -/// into the outbox table using raw SQL through the DbContext Npgsql connection. +/// Stores message envelopes in the PostgreSQL outbox. /// -/// -/// An active database or ambient transaction defers the outbox signal until commit. -/// A publish or send without a transaction throws when a transaction is required, -/// and otherwise signals immediately after insert. -/// internal sealed class PostgresMessageOutbox : IMessageOutbox, IDisposable { private readonly DbContext _originalDbContext; @@ -71,7 +65,7 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, } /// - /// Serializes the message envelope and inserts it into the Postgres outbox table. + /// Serializes the message envelope and stores it in the Postgres outbox table. /// /// /// With an active database transaction, the signal is deferred to the transaction commit interceptor. @@ -85,13 +79,9 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, /// public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken cancellationToken) { - if (_requireTransaction && !HasTransaction() && RequiresTransaction(envelope)) + if (_requireTransaction && RequiresTransaction(envelope) && !HasTransaction()) { - throw new InvalidOperationException( - $"The outbox for DbContext '{_originalDbContext.GetType().FullName}' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " - + "or set RequireTransaction to false in UsePostgresOutbox()."); + throw ThrowHelper.OutboxRequiresTransaction(_originalDbContext.GetType()); } await _semaphore.WaitAsync(cancellationToken); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs new file mode 100644 index 00000000000..d4f2f070541 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; +using Mocha.EntityFrameworkCore; + +namespace Mocha.Outbox; + +internal static class ThrowHelper +{ + public static InvalidOperationException OutboxRequiresTransaction(Type contextType) + => new( + $"{nameof(IMessageBus)} publishes and sends are stored in the outbox of the first {nameof(DbContext)} " + + $"registered with {nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}(), " + + $"'{contextType.FullName}', and require a transaction on that {nameof(DbContext)}. " + + $"Begin a transaction on it, use {nameof(EntityFrameworkCoreBuilderExtensions.UseTransaction)}() " + + "on it for consumers, " + + $"or set {nameof(PostgresOutboxOptions.RequireTransaction)} to false in " + + $"{nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}()."); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index 4e37adb402d..e4e31244d92 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -43,10 +43,10 @@ public static IMessageBusHostBuilder AddEntityFramework( services.GetService(), services.GetTimeProvider())); - builder.Services.AddSingleton< + builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< IDbContextOptionsConfiguration, MessagingDbContextOptionsConfiguration - >(); + >()); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs new file mode 100644 index 00000000000..be44e32d8a9 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbContextRegistration.cs @@ -0,0 +1,3 @@ +namespace Mocha.EntityFrameworkCore; + +internal sealed record OutboxDbContextRegistration(Type ContextType); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs index 7ca644ec213..c734e847d3a 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -18,6 +18,15 @@ public static class OutboxEntityFrameworkCorePersistenceBuilderExtensions /// The same instance for chaining. public static IEntityFrameworkCoreBuilder UseOutboxCore(this IEntityFrameworkCoreBuilder builder) { + if (builder.Services.Any(descriptor => + descriptor.ServiceType == typeof(OutboxDbContextRegistration) + && descriptor.ImplementationInstance is OutboxDbContextRegistration registration + && registration.ContextType == builder.ContextType)) + { + return builder; + } + + builder.Services.AddSingleton(new OutboxDbContextRegistration(builder.ContextType)); builder.HostBuilder.UseOutboxCore(); builder.ConfigureEntityFrameworkServices(static services => diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs index 5ebe57bf66d..c718b69e1da 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs @@ -35,6 +35,26 @@ public void UsePostgresOutbox_Should_DeferConfiguration_When_OptionsHaveNotBeenR Assert.Equal(1, configureCount); } + [Fact] + public async Task UsePostgresOutbox_Should_RegisterOnce_When_ConfigurationIsRepeated() + { + // arrange + var services = CreateServices(); + var builder = services.AddMessageBus(); + builder.AddInMemory(); + builder.AddEntityFramework(ef => ef.UseOutboxCore()); + + // act + builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); + builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); + await using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await using var scope = provider.CreateAsyncScope(); + + // assert + Assert.Single(provider.GetServices().OfType()); + Assert.IsType(scope.ServiceProvider.GetRequiredService()); + } + [Fact] public async Task UsePostgresOutbox_Should_RegisterHostedService_When_Called() { @@ -81,16 +101,20 @@ public async Task UsePostgresOutbox_Should_RegisterScopedOutbox_When_Called() } [Fact] - public async Task UsePostgresOutbox_Should_RegisterProcessor_When_Called() + public async Task UsePostgresOutbox_Should_RegisterKeyedSingletonProcessor_When_Called() { - // Arrange + // arrange await using var provider = BuildProvider(); + await using var scope = provider.CreateAsyncScope(); - // Act - var processor = provider.GetService(); + // act + var processor = provider.GetRequiredKeyedService(typeof(TestDbContext)); - // Assert - Assert.NotNull(processor); + // assert + Assert.Same( + processor, + scope.ServiceProvider.GetRequiredKeyedService(typeof(TestDbContext))); + Assert.Null(provider.GetService()); } [Fact] @@ -116,24 +140,25 @@ public async Task UsePostgresOutbox_Should_ConfigureQueriesFromModel_When_Defaul private static ServiceProvider BuildProvider() { - var services = new ServiceCollection(); - services.AddLogging(); - services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); - - // Use a resilient signal to prevent ObjectDisposedException when - // EF Core shares the internal service provider (and interceptors) - // across test classes via ShouldUseSameServiceProvider. - services.AddSingleton(); - + var services = CreateServices(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox()); builder.AddInMemory(); var provider = services.BuildServiceProvider(); - // Build the runtime so that all singleton factories resolve _ = provider.GetRequiredService(); return provider; } + + private static ServiceCollection CreateServices() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); + services.AddSingleton(); + + return services; + } } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs new file mode 100644 index 00000000000..a654522824c --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs @@ -0,0 +1,292 @@ +using System.Collections.Concurrent; +using System.Data; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresMultipleContextOutboxTests(PostgresFixture fixture) : IClassFixture +{ + private static CancellationToken TestToken => TestContext.Current.CancellationToken; + + [Fact] + public async Task Set_Should_WakeEveryOutboxProcessor_When_MultipleContextsAreIdle() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + + // Initialize the schemas without outbox interceptors. + await using (var first = new FirstDbContext(new DbContextOptionsBuilder() + .UseTestNpgsql(firstConnection).Options)) + { + await first.Database.EnsureCreatedAsync(TestToken); + } + + await using (var second = new SecondDbContext(new DbContextOptionsBuilder() + .UseTestNpgsql(secondConnection).Options)) + { + await second.Database.EnsureCreatedAsync(TestToken); + } + + await using var provider = await CreateProviderAsync(firstConnection, secondConnection, wakeOnlyOnSignal: true); + var firstIdle = ObserveFirstPollCompletion(provider); + var secondIdle = ObserveFirstPollCompletion(provider); + var signal = provider.GetRequiredService(); + var runtime = provider.GetRequiredService(); + var type = runtime.GetMessageType(typeof(ContextEvent)); + var endpoint = runtime.GetPublishEndpoint(type); + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + await Task.WhenAll(firstIdle, secondIdle).WaitAsync(TimeSpan.FromSeconds(30), TestToken); + foreach (var (connection, context) in new[] { (firstConnection, "first"), (secondConnection, "second") }) + { + await MessageRows.InsertOutboxAsync(connection, new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = type.Identity, + ContentType = MessageContentType.Json.Value, + DestinationAddress = endpoint.Address.ToString(), + Body = JsonSerializer.SerializeToUtf8Bytes(new ContextEvent(context)) + }, TestToken); + } + + // act + signal.Set(); + var recorder = provider.GetRequiredService(); + await recorder.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestToken); + + // assert + Assert.Equal(["first", "second"], recorder.Messages.Order().ToArray()); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + + [Fact] + public async Task PublishAsync_Should_PersistToFirstRegisteredContext_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + await using var scope = provider.CreateAsyncScope(); + var first = scope.ServiceProvider.GetRequiredService(); + var bus = scope.ServiceProvider.GetRequiredService(); + var recorder = provider.GetRequiredService(); + await using var transaction = await first.Database.BeginTransactionAsync(TestToken); + + // act + await bus.PublishAsync(new ContextEvent("default"), TestToken); + var beforeCommit = await CountRowsAsync(provider); + await transaction.CommitAsync(TestToken); + var afterCommit = await CountRowsAsync(provider); + + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + while (recorder.Messages.IsEmpty) + { + await Task.Delay(25, timeout.Token); + } + + // assert + Assert.Equal((0, 0), beforeCommit); + Assert.Equal((1, 0), afterCommit); + Assert.Equal(["default"], recorder.Messages.ToArray()); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + + [Fact] + public async Task RequestAsync_Should_ReturnResponse_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync( + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + var workers = provider.GetServices().OfType().ToArray(); + foreach (var worker in workers) + { + await worker.StartAsync(TestToken); + } + + try + { + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + + // act + var response = await bus.RequestAsync(new ContextRequest("request"), TestToken) + .AsTask() + .WaitAsync(TimeSpan.FromSeconds(30), TestToken); + + // assert + Assert.Equal("request", response.Context); + } + finally + { + foreach (var worker in workers) + { + await worker.StopAsync(TestToken); + } + } + } + + private static Task ObserveFirstPollCompletion(ServiceProvider provider) + where TContext : DbContext + { + var completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var options = provider.GetRequiredService>() + .Get(typeof(TContext).FullName); + var createConnection = options.CreateConnection; + options.CreateConnection = services => + { + var connection = createConnection(services); + connection.StateChange += (_, args) => + { + if (args.CurrentState == ConnectionState.Closed) + { + completed.TrySetResult(); + } + }; + return connection; + }; + return completed.Task; + } + + private static async Task<(int First, int Second)> CountRowsAsync(ServiceProvider provider) + { + await using var scope = provider.CreateAsyncScope(); + var first = await scope.ServiceProvider.GetRequiredService() + .Set().CountAsync(TestToken); + var second = await scope.ServiceProvider.GetRequiredService() + .Set().CountAsync(TestToken); + return (first, second); + } + + // With wakeOnlyOnSignal the relays poll every 10 minutes and no consumer transaction commits, so only the + // outbox signal wakes an idle relay. + private static async Task CreateProviderAsync( + string firstConnection, + string secondConnection, + bool wakeOnlyOnSignal) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + services.AddDbContextFactory(options => options.UseTestNpgsql(firstConnection)); + services.AddDbContext(options => options.UseTestNpgsql(secondConnection)); + var builder = services.AddMessageBus(); + Action configureOutbox = wakeOnlyOnSignal + ? static options => options.PollingInterval = TimeSpan.FromMinutes(10) + : static _ => { }; + builder.AddEntityFramework(ef => + { + ef.UsePostgresOutbox(configureOutbox); + if (!wakeOnlyOnSignal) + { + ef.UseTransaction(); + } + }); + builder.AddEntityFramework(ef => ef.UsePostgresOutbox(configureOutbox)); + builder.AddEventHandler(); + builder.AddRequestHandler(); + builder.AddInMemory(); + + var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + await ((MessagingRuntime)provider.GetRequiredService()).StartAsync(TestToken); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + await scope.ServiceProvider.GetRequiredService().Database.EnsureCreatedAsync(TestToken); + return provider; + } + + public sealed record ContextEvent(string Context); + + public sealed record ContextRequest(string Context) : IEventRequest; + + public sealed record ContextResponse(string Context); + + public sealed class ContextRequestHandler : IEventRequestHandler + { + public ValueTask HandleAsync(ContextRequest request, CancellationToken cancellationToken) + => new(new ContextResponse(request.Context)); + } + + public sealed class ContextEventHandler( + MessageRecorder recorder, + FirstDbContext first, + SecondDbContext second) : IEventHandler + { + public ValueTask HandleAsync(ContextEvent message, CancellationToken cancellationToken) + { + recorder.Transactions.Enqueue(( + first.Database.CurrentTransaction is not null, + second.Database.CurrentTransaction is not null)); + recorder.Messages.Enqueue(message.Context); + if (recorder.Messages.Count == 2) + { + recorder.Completed.TrySetResult(); + } + + return default; + } + } + + public sealed class MessageRecorder + { + public ConcurrentQueue Messages { get; } = new(); + + public ConcurrentQueue<(bool First, bool Second)> Transactions { get; } = new(); + + public TaskCompletionSource Completed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + public sealed class FirstDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.AddPostgresOutbox(); + } + + public sealed class SecondDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.AddPostgresOutbox(); + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs index 7b37d89c9a3..d66bb009ca7 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxDataSourceTests.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Outbox; using Mocha.Transport.InMemory; @@ -28,7 +29,7 @@ public async Task Worker_Should_DeliverCommittedMessage_When_ContextUsesPassword await using var provider = await CreateProviderAsync( connectionString, configuration == ConnectionConfiguration.ConnectionString ? null : dataSource); var delivered = provider.GetRequiredService>(); - var worker = provider.GetRequiredService(); + var worker = provider.GetServices().OfType().Single(); // act int committedCount; @@ -88,7 +89,7 @@ public async Task Worker_Should_ReleaseConnection_When_Idle() }.ConnectionString; await using var provider = await CreateProviderAsync(connectionString, dataSource: null); var delivered = provider.GetRequiredService>(); - var worker = provider.GetRequiredService(); + var worker = provider.GetServices().OfType().Single(); await using (var scope = provider.CreateAsyncScope()) { await scope.ServiceProvider.GetRequiredService() diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs new file mode 100644 index 00000000000..74fa1fd98cf --- /dev/null +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs @@ -0,0 +1,108 @@ +#if NET9_0_OR_GREATER +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; +#endif +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Outbox; +using Mocha.Transport.InMemory; + +namespace Mocha.EntityFrameworkCore.Postgres.Tests; + +public sealed class PostgresOutboxRepeatedRegistrationTests +{ + private const string ConnectionString = "Host=localhost;Database=test"; + +#if NET9_0_OR_GREATER + [Fact] + public async Task UsePostgresOutbox_Should_RegisterEachInterceptorOnce_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(), + ef => ef.UsePostgresOutbox()); + await using var scope = provider.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); + + // act + var interceptors = dbContext.GetService>() + .Select(interceptor => interceptor.GetType().Name) + .Order(StringComparer.Ordinal); + + // assert + Assert.Equal( + ["OutboxDbTransactionInterceptor", "OutboxSaveChangesInterceptor"], + interceptors); + } +#endif + + [Fact] + public async Task UsePostgresOutbox_Should_RegisterOneProcessorWorkerAndValidator_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(), + ef => ef.UsePostgresOutbox()); + + // act + var processors = provider.GetKeyedServices(typeof(TestDbContext)).Count(); + var workers = provider.GetServices().OfType().Count(); + var validators = provider.GetServices>().Count(); + + // assert + Assert.Equal(1, processors); + Assert.Equal(1, workers); + Assert.Equal(1, validators); + } + + [Fact] + public async Task UsePostgresOutbox_Should_ValidateSecondConfiguration_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1)), + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.Zero)); + var monitor = provider.GetRequiredService>(); + + // act + var exception = Assert.Throws(() => monitor.Get(typeof(TestDbContext).FullName)); + + // assert + Assert.Equal( + "PostgresOutboxOptions.PollingInterval must be greater than zero.", + exception.Message); + } + + [Fact] + public async Task UsePostgresOutbox_Should_ApplySecondConfiguration_When_CalledTwiceForOneContext() + { + // arrange + await using var provider = BuildProvider( + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1)), + ef => ef.UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(2))); + var monitor = provider.GetRequiredService>(); + + // act + var options = monitor.Get(typeof(TestDbContext).FullName); + + // assert + Assert.Equal(TimeSpan.FromSeconds(2), options.PollingInterval); + } + + private static ServiceProvider BuildProvider( + Action first, + Action second) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(options => options.UseTestNpgsql(ConnectionString)); + var builder = services.AddMessageBus(); + builder.AddInMemory(); + builder.AddEntityFramework(first); + builder.AddEntityFramework(second); + + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } +} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs index 0734846c2d0..17c4b847227 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRetryTests.cs @@ -305,7 +305,9 @@ private static async Task CreateProviderAsync( private static RunningProcessor StartProcessor(IServiceProvider provider) { var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestToken); - var processing = provider.GetRequiredService().ProcessAsync(cancellation.Token); + var processing = provider + .GetRequiredKeyedService(typeof(TestDbContext)) + .ProcessAsync(cancellation.Token); return new RunningProcessor(processing, cancellation); } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs index 0e6ada60e85..55ad81dbb7b 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs @@ -11,6 +11,14 @@ namespace Mocha.EntityFrameworkCore.Postgres.Tests; public sealed class PostgresOutboxTransactionTests(PostgresFixture fixture) : IClassFixture { + private const string RequiresTransactionMessage = + "IMessageBus publishes and sends are stored in the outbox of the first DbContext registered with " + + "UsePostgresOutbox(), " + + "'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext', " + + "and require a transaction on that DbContext. " + + "Begin a transaction on it, use UseTransaction() on it for consumers, " + + "or set RequireTransaction to false in UsePostgresOutbox()."; + private static CancellationToken TestToken => TestContext.Current.CancellationToken; [Fact] @@ -28,12 +36,7 @@ public async Task PublishAsync_Should_Throw_When_TransactionIsRequiredAndNoneIsA async () => await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken)); // assert - Assert.Equal( - "The outbox for DbContext 'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " - + "or set RequireTransaction to false in UsePostgresOutbox().", - exception.Message); + Assert.Equal(RequiresTransactionMessage, exception.Message); Assert.Equal(0, await CountOutboxRowsAsync(connectionString)); } @@ -128,9 +131,11 @@ public async Task PersistAsync_Should_Throw_When_PublishOrSendHasNoTransaction(s // assert Assert.Equal( - "The outbox for DbContext 'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext' " - + "requires a transaction to publish or send a message. " - + "Begin a transaction on that DbContext, use UseTransaction() for consumers, " + "IMessageBus publishes and sends are stored in the outbox of the first DbContext registered with " + + "UsePostgresOutbox(), " + + "'Mocha.EntityFrameworkCore.Postgres.Tests.PostgresOutboxTransactionTests+TransactionDbContext', " + + "and require a transaction on that DbContext. " + + "Begin a transaction on it, use UseTransaction() on it for consumers, " + "or set RequireTransaction to false in UsePostgresOutbox().", exception.Message); Assert.Equal(0, await CountOutboxRowsAsync(connectionString)); From 8bc2cf90825453568a272e2ea3fea04deeade27f Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:04:12 +0000 Subject: [PATCH 05/13] [Mocha] Say how to register the DbContext when the outbox cannot resolve it When the DbContext of an outbox was not registered as a service, for example with AddPooledDbContextFactory before EF Core 10, resolving the processor failed with the container's missing service error. The outbox now throws an InvalidOperationException that names the context and the registrations that make it resolvable. --- .../OutboxServiceCollectionExtensions.cs | 4 ++-- .../Outbox/PostgresMessageOutbox.cs | 6 ++++- .../Outbox/ThrowHelper.cs | 15 ++++++++++++ .../OutboxServiceRegistrationTests.cs | 23 +++++++++++++++++++ 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 08b50d7431b..1cca755bd05 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -59,7 +59,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( .Configure((options, sp) => { using var scope = sp.CreateScope(); - var dbContext = (DbContext)scope.ServiceProvider.GetRequiredService(contextType); + var dbContext = PostgresMessageOutbox.ResolveDbContext(scope.ServiceProvider, contextType); var model = dbContext.Model; ConfigureOutboxTableInfo(options.Outbox, model); @@ -71,7 +71,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { options.CreateConnection = services => { - var dbContext = (DbContext)services.GetRequiredService(contextType); + var dbContext = PostgresMessageOutbox.ResolveDbContext(services, contextType); return (NpgsqlConnection)((ICloneable)dbContext.Database.GetDbConnection()).Clone(); }; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index c5ed0a39efa..132e1cfa3c3 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -54,7 +54,7 @@ public PostgresMessageOutbox( /// A new configured for the specified DbContext. public static PostgresMessageOutbox Create(Type contextType, string optionsName, IServiceProvider services) { - var dbContext = (DbContext)services.GetRequiredService(contextType); + var dbContext = ResolveDbContext(services, contextType); var signal = services.GetRequiredService(); var outboxOptionsMonitor = services.GetRequiredService>(); var outboxOptions = outboxOptionsMonitor.Get(optionsName); @@ -64,6 +64,10 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, return new PostgresMessageOutbox(dbContext, signal, insertSql, options.RequireTransaction); } + internal static DbContext ResolveDbContext(IServiceProvider services, Type contextType) + => (DbContext?)services.GetService(contextType) + ?? throw ThrowHelper.OutboxDbContextNotRegistered(contextType); + /// /// Serializes the message envelope and stores it in the Postgres outbox table. /// diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs index d4f2f070541..cd541c55c7e 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs @@ -1,4 +1,5 @@ using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using Mocha.EntityFrameworkCore; namespace Mocha.Outbox; @@ -14,4 +15,18 @@ public static InvalidOperationException OutboxRequiresTransaction(Type contextTy + "on it for consumers, " + $"or set {nameof(PostgresOutboxOptions.RequireTransaction)} to false in " + $"{nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}()."); + + public static InvalidOperationException OutboxDbContextNotRegistered(Type contextType) + => new( + $"The {nameof(DbContext)} '{contextType.FullName}' is not registered as a service. " + + $"Register it with {nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextPool)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextFactory)} or " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)}. " + + $"Before EF Core 10, {nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)} " + + "does not register the context itself; also add " + + $"services.{nameof(ServiceCollectionServiceExtensions.AddScoped)}(sp => " + + $"sp.{nameof(ServiceProviderServiceExtensions.GetRequiredService)}" + + $"<{nameof(IDbContextFactory)}<{contextType.Name}>>()" + + $".{nameof(IDbContextFactory.CreateDbContext)}())."); } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs index c718b69e1da..cf1ec4e4cf5 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs @@ -55,6 +55,29 @@ public async Task UsePostgresOutbox_Should_RegisterOnce_When_ConfigurationIsRepe Assert.IsType(scope.ServiceProvider.GetRequiredService()); } + [Fact] + public async Task UsePostgresOutbox_Should_ThrowClearError_When_ContextIsNotRegistered() + { + // arrange + var services = new ServiceCollection(); + services.AddLogging(); + services.AddMessageBus().AddEntityFramework(ef => ef.UsePostgresOutbox()).AddInMemory(); + await using var provider = services.BuildServiceProvider(); + + // act + var exception = Assert.Throws( + () => provider.GetRequiredKeyedService(typeof(TestDbContext))); + + // assert + Assert.Equal( + $"The DbContext '{typeof(TestDbContext).FullName}' is not registered as a service. " + + "Register it with AddDbContext, AddDbContextPool, AddDbContextFactory or AddPooledDbContextFactory. " + + "Before EF Core 10, AddPooledDbContextFactory does not register the context itself; also add " + + "services.AddScoped(sp => sp.GetRequiredService>()" + + ".CreateDbContext()).", + exception.Message); + } + [Fact] public async Task UsePostgresOutbox_Should_RegisterHostedService_When_Called() { From 3e3517feea4577bbb2b81983f5735a236541353d Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:04:55 +0000 Subject: [PATCH 06/13] [Mocha] Fix the outbox treating an ambient transaction as joined when its connection did not enlist PostgresMessageOutbox accepted a publish as transactional whenever Transaction.Current was set. With Enlist=false in the connection string the connection does not join the ambient transaction, so the outbox row was written outside it and stayed when the scope rolled back. The check now asks the transaction manager of the context. A publish on a connection that has not joined throws the transaction-required exception, and a transaction enlisted through Database.EnlistTransaction without an ambient one is accepted. --- .../Outbox/PostgresMessageOutbox.cs | 13 ++++- .../PostgresOutboxTransactionTests.cs | 50 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index 132e1cfa3c3..4d25d01a618 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Transactions; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -131,7 +132,17 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken } private bool HasTransaction() - => _originalDbContext.Database.CurrentTransaction is not null || Transaction.Current is not null; + => _originalDbContext.Database.CurrentTransaction is not null + || HasSystemTransaction(_originalDbContext); + + /// + /// Returns whether the connection of the context takes part in a , either enlisted + /// explicitly or joined as the ambient transaction. + /// + private static bool HasSystemTransaction(DbContext context) + => context.GetService() is ITransactionEnlistmentManager manager + ? manager.EnlistedTransaction is not null || manager.CurrentAmbientTransaction is not null + : Transaction.Current is not null; // Replies and faults can be dispatched after the handler transaction rolls back. private static bool RequiresTransaction(MessageEnvelope envelope) diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs index 55ad81dbb7b..b1146173e97 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs @@ -40,6 +40,56 @@ public async Task PublishAsync_Should_Throw_When_TransactionIsRequiredAndNoneIsA Assert.Equal(0, await CountOutboxRowsAsync(connectionString)); } + [Fact] + public async Task PublishAsync_Should_Throw_When_ConnectionDoesNotJoinAmbientTransaction() + { + // arrange + var connectionString = + new NpgsqlConnectionStringBuilder(await fixture.CreateDatabaseAsync()) { Enlist = false }.ConnectionString; + await using var provider = await CreateProviderAsync(connectionString, new StubOutboxSignal()); + await EnsureCreatedAsync(provider); + InvalidOperationException exception; + + // act + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + exception = await Assert.ThrowsAsync( + async () => await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken)); + } + + var rowsAfterRollback = await CountOutboxRowsAsync(connectionString); + + // assert + Assert.Equal(RequiresTransactionMessage, exception.Message); + Assert.Equal(0, rowsAfterRollback); + } + + [Fact] + public async Task PublishAsync_Should_InsertRowWithTransaction_When_ConnectionIsEnlistedWithoutAmbientTransaction() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + await using var provider = await CreateProviderAsync(connectionString, new StubOutboxSignal()); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + using var transaction = new CommittableTransaction(); + await db.Database.OpenConnectionAsync(TestToken); + db.Database.EnlistTransaction(transaction); + + // act + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + var rowsBeforeCommit = await CountOutboxRowsAsync(connectionString); + transaction.Commit(); + var rowsAfterCommit = await CountOutboxRowsAsync(connectionString); + + // assert + Assert.Equal((0L, 1L), (rowsBeforeCommit, rowsAfterCommit)); + } + [Fact] public async Task PublishAsync_Should_InsertRowImmediately_When_TransactionIsNotRequired() { From 07eab277c545672aa0191ae8b3053770cbc4b6de Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:04:55 +0000 Subject: [PATCH 07/13] [Mocha] Document the outbox with several DbContexts and add the 16.8 upgrade notes The reliability page says when the outbox processor is woken at once and when it finds a message at its next check, how to configure the polling interval, and which context IMessageBus publishes use when several contexts have an outbox. The migration guide covers the keyed outbox processors, the internal EF Core registration types, UseTransaction() using its own context, the idle check, and EF Core services being shared across hosts. --- .../migration/migrate-from-16-7-to-16-8.md | 34 ++++++++++++++++++- website/content/docs/mocha/reliability.md | 6 ++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index 5b6e6f9126e..93bfb5ab081 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -1,6 +1,6 @@ --- title: Migrate Mocha from 16.7 to 16.8 -description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, source generator changes, and the health check, log, and trace changes that monitoring depends on." +description: "Migration guide for Mocha v16.7 to v16.8: RabbitMQ publisher confirms, publish and start timeouts, connection and consumer recovery, Postgres outbox retry rules, keyed outbox processors, Entity Framework Core registration changes, source generator changes, and the health check, log, and trace changes that monitoring depends on." --- Update every `Mocha.*` package in the application to version 16.8 before applying these changes. @@ -32,6 +32,24 @@ Assemblies that call or implement these methods must be recompiled against 16.8. `OutboxDispatchContextExtensions.SkipOutbox()` and `OutboxMiddlewareFeature` are removed. The outbox processor and the scheduler workers send a stored message directly to the transport and no longer set the feature. There is no replacement for sending a single dispatch to the transport without storing it in the outbox. +## `ConfigureEntityFrameworkServices` and `MessagingDbContextOptions` are internal + +`ConfigureEntityFrameworkServices` and `MessagingDbContextOptions` are no longer public. To add your own services to a DbContext, use Entity Framework Core's `AddInterceptors` or `ReplaceService` when configuring the context. + +## Resolve PostgreSQL outbox processors by DbContext type + +`PostgresOutboxProcessor` is now registered only as a keyed singleton, with the registered DbContext type as its key. Replace unkeyed calls such as `GetRequiredService()` with: + +```csharp +using Microsoft.Extensions.DependencyInjection; +using Mocha.Outbox; + +var processor = serviceProvider.GetRequiredKeyedService( + typeof(AppDbContext)); +``` + +The host runs an outbox processor for each context registered with `UsePostgresOutbox()`. In 16.7 it ran only the outbox processor of the context registered last. `IMessageBus` publishes and sends, and the replies and faults Mocha sends from handlers, use the outbox of the first context registered with `UsePostgresOutbox()`. + # Behavioral breaking changes ## Dispatch middleware runs once for a stored message @@ -293,6 +311,20 @@ What you will observe: - For a temporary endpoint, the forwarding subscriptions and the queue are removed after the processor is disposed. When this takes longer than 30 seconds, the log shows the Warning `Deleting the temporary resources of Azure Service Bus queue '' did not complete within 00:00:30` and the stop continues. - Disposing the processor waits for running handlers. A handler that ignores its `CancellationToken` delays the stop until it returns. +## `UseTransaction()` uses its own DbContext + +`UseTransaction()` opens the consumer transaction on the DbContext of the `AddEntityFramework` call it is configured on. Previously it used the context of the last `AddEntityFramework` call. + +## The outbox processor checks for messages when idle + +Each outbox processor now checks the database for new messages when it has not been notified for `PollingInterval`, ten seconds by default. This delivers messages committed outside Entity Framework Core, for example by another process. On .NET 8, where Mocha's Entity Framework Core interceptors are not applied, it also delivers messages written in an Entity Framework Core transaction. Configure the interval with `UsePostgresOutbox(options => options.PollingInterval = ...)`. + +## Entity Framework Core services are shared across hosts + +Contexts registered with `AddEntityFramework` now share Entity Framework Core's internal service provider, and with it the model cache, across the hosts in one process, under the same rules as contexts without Mocha. In 16.7 each host had its own internal service provider. + +When `OnModelCreating` depends on a value that differs per host, for example a schema injected into the context, every host uses the model that was built first, and the outbox processor of every host uses the outbox table of that model. Replace Entity Framework Core's `IModelCacheKeyFactory` with one that adds the value to the cache key. See [Alternating between multiple models with the same DbContext type](https://learn.microsoft.com/ef/core/modeling/dynamic-model). + ## The source generator registers message types differently - An assembly that publishes or sends messages through `IMessageBus` but has no handlers or sagas now gets a generated `Add{Module}()` method, which registers the message types it publishes or sends that are declared in the same assembly. Message types from a referenced assembly, such as a contracts project, are not registered by call sites. The compile-time type of the message argument decides what is registered: a call that passes the message as an interface, an abstract class, or `object` registers nothing. See [Module naming](../handler-registration.md#module-naming). diff --git a/website/content/docs/mocha/reliability.md b/website/content/docs/mocha/reliability.md index 4a8e6a54f9f..c52d1dc7c37 100644 --- a/website/content/docs/mocha/reliability.md +++ b/website/content/docs/mocha/reliability.md @@ -757,13 +757,15 @@ public class OrderPlacedHandler(AppDbContext dbContext, IMessageBus bus) } ``` -After the transaction commits, the outbox processor detects the new message (via EF Core interceptors that signal on save and transaction commit) and dispatches it to the transport. +After the transaction commits, the outbox processor dispatches the new message to the transport. On .NET 9 and later, a save or commit through EF Core wakes the outbox processor at once. On .NET 8, after a commit made directly through an externally owned database transaction, and after the commit of a transaction enlisted with `Database.EnlistTransaction`, the outbox processor finds the message the next time it checks the database. + +Without a notification, the outbox processor waits up to ten seconds before checking the database for messages to send. Configure this wait with `UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1))`. ## Transaction requirements By default, the outbox requires a transaction for `PublishAsync` and `SendAsync`. Without an open database transaction on the DbContext or an ambient `TransactionScope`, these calls throw an `InvalidOperationException` and no message is written. Replies and faults are written without a transaction. -Direct bus publishes use the first DbContext registered with `UsePostgresOutbox()`. A transaction on another DbContext does not satisfy this requirement. +With more than one outbox context, `IMessageBus` publishes and sends, and the replies and faults Mocha sends from handlers, use the outbox of the first context registered with `UsePostgresOutbox()`. The transaction must be open on that context. A transaction on another DbContext does not satisfy this requirement, and `UseTransaction()` on another context does not cover `IMessageBus` publishes. Each outbox context has its own outbox processor. Inside a transaction, the message is written to the outbox table as part of that transaction. Consumers get a transaction from `UseTransaction()`, and mediator handlers from `UseEntityFrameworkTransactions()`. In other code, open one on the DbContext: From 3b8d3030272691e7dda499506d2d843c3e395844 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:11:41 +0000 Subject: [PATCH 08/13] [Mocha] Read the polling interval from the outbox processor options --- .../Outbox/OutboxProcessor.cs | 12 ++++-------- .../Outbox/OutboxServiceCollectionExtensions.cs | 8 ++++---- .../Outbox/PostgresMessageOutboxOptions.cs | 5 +++++ 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs index 515398e0490..f8df68805fa 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxProcessor.cs @@ -20,7 +20,6 @@ public sealed class PostgresOutboxProcessor private readonly ObjectPool _contextPool; private readonly PostgresMessageOutboxOptions _options; private readonly TimeProvider _timeProvider; - private readonly TimeSpan _pollingInterval; /// /// Initializes a new instance of the class. @@ -41,17 +40,15 @@ public sealed class PostgresOutboxProcessor /// The signal used to wake the processor when new outbox messages are enqueued. /// /// - /// The outbox options containing the SQL queries and connection factory. + /// The options for this outbox processor. /// - /// How long an idle worker waits before checking for messages to send. internal PostgresOutboxProcessor( ILogger logger, IServiceProvider services, IMessagingRuntime runtime, IMessagingPools pools, IOutboxSignal signal, - PostgresMessageOutboxOptions options, - TimeSpan pollingInterval) + PostgresMessageOutboxOptions options) { _logger = logger; _services = services; @@ -60,7 +57,6 @@ internal PostgresOutboxProcessor( _contextPool = pools.DispatchContext; _options = options; _timeProvider = services.GetTimeProvider(); - _pollingInterval = pollingInterval; } /// @@ -79,9 +75,9 @@ public async Task ProcessAsync(CancellationToken cancellationToken) while (!cancellationToken.IsCancellationRequested) { var nextPollingInterval = await ProcessPendingAsync(cancellationToken); - var delay = _pollingInterval; + var delay = _options.PollingInterval; - if (nextPollingInterval is { } interval && interval < _pollingInterval) + if (nextPollingInterval is { } interval && interval < delay) { delay = interval; _logger.OutboxProcessorSleeping(delay); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 1cca755bd05..1aa7c10d981 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -77,21 +77,21 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( var tableInfo = tableInfoMonitor.Get(builder.Name); options.Queries = PostgresMessageOutboxQueries.From(tableInfo.Outbox); - }); + }) + .Configure>((options, outboxOptions) => + options.PollingInterval = outboxOptions.Get(builder.Name).PollingInterval); builder.Services.AddKeyedSingleton(contextType, (sp, _) => { var optionsMonitor = sp.GetRequiredService>(); var options = optionsMonitor.Get(builder.Name); - var outboxOptions = sp.GetRequiredService>().Get(builder.Name); return new PostgresOutboxProcessor( sp.GetRequiredService>(), sp, sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), - options, - outboxOptions.PollingInterval); + options); }); builder.Services.AddSingleton(sp => diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs index a1971b7da30..de3cf533c82 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutboxOptions.cs @@ -24,6 +24,11 @@ internal sealed class PostgresMessageOutboxOptions /// public int CriticalAttemptInterval { get; set; } = 10; + /// + /// Gets or sets how long an idle processor waits before checking for messages when no notification arrives. + /// + public TimeSpan PollingInterval { get; set; } + /// /// Gets or sets how long the processor waits before it looks again for a due message that another /// instance holds. From 0fb19f4214d0e567c3d95ccd3b781d170796981f Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:25:49 +0000 Subject: [PATCH 09/13] [Mocha] Move the outbox's DbContext lookup to a service provider extension PostgresMessageOutbox carried the lookup of a DbContext by its runtime type as an internal static, and the outbox registration called into the store class for it. The lookup is now GetRequiredDbContext on IServiceProvider in Mocha.EntityFrameworkCore, the project that owns the context type of the builder. Its exception moves to that project's ThrowHelper as DbContextNotRegistered and keeps its message. --- .../OutboxServiceCollectionExtensions.cs | 4 ++-- .../Outbox/PostgresMessageOutbox.cs | 6 +----- .../Outbox/ThrowHelper.cs | 15 ------------- .../DbContextServiceProviderExtensions.cs | 13 ++++++++++++ .../Mocha.EntityFrameworkCore/ThrowHelper.cs | 21 +++++++++++++++++++ 5 files changed, 37 insertions(+), 22 deletions(-) create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 1aa7c10d981..652dfff5a7f 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -59,7 +59,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( .Configure((options, sp) => { using var scope = sp.CreateScope(); - var dbContext = PostgresMessageOutbox.ResolveDbContext(scope.ServiceProvider, contextType); + var dbContext = scope.ServiceProvider.GetRequiredDbContext(contextType); var model = dbContext.Model; ConfigureOutboxTableInfo(options.Outbox, model); @@ -71,7 +71,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( { options.CreateConnection = services => { - var dbContext = PostgresMessageOutbox.ResolveDbContext(services, contextType); + var dbContext = services.GetRequiredDbContext(contextType); return (NpgsqlConnection)((ICloneable)dbContext.Database.GetDbConnection()).Clone(); }; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index 4d25d01a618..e5199e5e0da 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -55,7 +55,7 @@ public PostgresMessageOutbox( /// A new configured for the specified DbContext. public static PostgresMessageOutbox Create(Type contextType, string optionsName, IServiceProvider services) { - var dbContext = ResolveDbContext(services, contextType); + var dbContext = services.GetRequiredDbContext(contextType); var signal = services.GetRequiredService(); var outboxOptionsMonitor = services.GetRequiredService>(); var outboxOptions = outboxOptionsMonitor.Get(optionsName); @@ -65,10 +65,6 @@ public static PostgresMessageOutbox Create(Type contextType, string optionsName, return new PostgresMessageOutbox(dbContext, signal, insertSql, options.RequireTransaction); } - internal static DbContext ResolveDbContext(IServiceProvider services, Type contextType) - => (DbContext?)services.GetService(contextType) - ?? throw ThrowHelper.OutboxDbContextNotRegistered(contextType); - /// /// Serializes the message envelope and stores it in the Postgres outbox table. /// diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs index cd541c55c7e..d4f2f070541 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/ThrowHelper.cs @@ -1,5 +1,4 @@ using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using Mocha.EntityFrameworkCore; namespace Mocha.Outbox; @@ -15,18 +14,4 @@ public static InvalidOperationException OutboxRequiresTransaction(Type contextTy + "on it for consumers, " + $"or set {nameof(PostgresOutboxOptions.RequireTransaction)} to false in " + $"{nameof(OutboxServiceCollectionExtensions.UsePostgresOutbox)}()."); - - public static InvalidOperationException OutboxDbContextNotRegistered(Type contextType) - => new( - $"The {nameof(DbContext)} '{contextType.FullName}' is not registered as a service. " - + $"Register it with {nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext)}, " - + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextPool)}, " - + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextFactory)} or " - + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)}. " - + $"Before EF Core 10, {nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)} " - + "does not register the context itself; also add " - + $"services.{nameof(ServiceCollectionServiceExtensions.AddScoped)}(sp => " - + $"sp.{nameof(ServiceProviderServiceExtensions.GetRequiredService)}" - + $"<{nameof(IDbContextFactory)}<{contextType.Name}>>()" - + $".{nameof(IDbContextFactory.CreateDbContext)}())."); } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs new file mode 100644 index 00000000000..48d67a6108f --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/DbContextServiceProviderExtensions.cs @@ -0,0 +1,13 @@ +using Microsoft.EntityFrameworkCore; + +namespace Mocha.EntityFrameworkCore; + +internal static class DbContextServiceProviderExtensions +{ + /// + /// Gets the of the specified type, and throws when it is not registered. + /// + public static DbContext GetRequiredDbContext(this IServiceProvider services, Type contextType) + => (DbContext?)services.GetService(contextType) + ?? throw ThrowHelper.DbContextNotRegistered(contextType); +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs new file mode 100644 index 00000000000..d2a8cd6e843 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/ThrowHelper.cs @@ -0,0 +1,21 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Mocha.EntityFrameworkCore; + +internal static class ThrowHelper +{ + public static InvalidOperationException DbContextNotRegistered(Type contextType) + => new( + $"The {nameof(DbContext)} '{contextType.FullName}' is not registered as a service. " + + $"Register it with {nameof(EntityFrameworkServiceCollectionExtensions.AddDbContext)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextPool)}, " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddDbContextFactory)} or " + + $"{nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)}. " + + $"Before EF Core 10, {nameof(EntityFrameworkServiceCollectionExtensions.AddPooledDbContextFactory)} " + + "does not register the context itself; also add " + + $"services.{nameof(ServiceCollectionServiceExtensions.AddScoped)}(sp => " + + $"sp.{nameof(ServiceProviderServiceExtensions.GetRequiredService)}" + + $"<{nameof(IDbContextFactory)}<{contextType.Name}>>()" + + $".{nameof(IDbContextFactory.CreateDbContext)}())."); +} From 43d8aa4d2523071b59586f9068baf41b0749da14 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:10:47 +0000 Subject: [PATCH 10/13] [Mocha] Remove two entries from the 16.8 migration guide The guide listed ConfigureEntityFrameworkServices and MessagingDbContextOptions becoming internal, and PostgresOutboxProcessor being registered as a keyed singleton per DbContext type. Both entries are removed from the API breaking changes. --- .../migration/migrate-from-16-7-to-16-8.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md index 93bfb5ab081..1a9c380c522 100644 --- a/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md +++ b/website/content/docs/mocha/migration/migrate-from-16-7-to-16-8.md @@ -32,24 +32,6 @@ Assemblies that call or implement these methods must be recompiled against 16.8. `OutboxDispatchContextExtensions.SkipOutbox()` and `OutboxMiddlewareFeature` are removed. The outbox processor and the scheduler workers send a stored message directly to the transport and no longer set the feature. There is no replacement for sending a single dispatch to the transport without storing it in the outbox. -## `ConfigureEntityFrameworkServices` and `MessagingDbContextOptions` are internal - -`ConfigureEntityFrameworkServices` and `MessagingDbContextOptions` are no longer public. To add your own services to a DbContext, use Entity Framework Core's `AddInterceptors` or `ReplaceService` when configuring the context. - -## Resolve PostgreSQL outbox processors by DbContext type - -`PostgresOutboxProcessor` is now registered only as a keyed singleton, with the registered DbContext type as its key. Replace unkeyed calls such as `GetRequiredService()` with: - -```csharp -using Microsoft.Extensions.DependencyInjection; -using Mocha.Outbox; - -var processor = serviceProvider.GetRequiredKeyedService( - typeof(AppDbContext)); -``` - -The host runs an outbox processor for each context registered with `UsePostgresOutbox()`. In 16.7 it ran only the outbox processor of the context registered last. `IMessageBus` publishes and sends, and the replies and faults Mocha sends from handlers, use the outbox of the first context registered with `UsePostgresOutbox()`. - # Behavioral breaking changes ## Dispatch middleware runs once for a stored message From c893d72f3e09c442b0efef81d6a1dba25d69b1ac Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:37:09 +0000 Subject: [PATCH 11/13] [Mocha] Fix the outbox processor being woken by saves and commits that wrote no outbox message Every SaveChanges and every transaction commit on an outbox context signaled the outbox processor, so the processor queried the outbox table after each of them, whether or not a message was written. The outbox now marks its context when it writes a message inside a database transaction, and the commit interceptor signals only when the mark is set. OutboxSaveChangesInterceptor is removed, so a save no longer signals. An OutboxMessage entity that is added through the change tracker is found when the processor next checks the database. --- .../Outbox/PostgresMessageOutbox.cs | 10 +- .../Outbox/DbContextOutboxState.cs | 12 +++ .../Outbox/OutboxDbTransactionInterceptor.cs | 18 +++- ...ameworkCorePersistenceBuilderExtensions.cs | 8 +- .../Outbox/OutboxSaveChangesInterceptor.cs | 35 ------- ...gresOutboxAmbientTransactionSignalTests.cs | 26 ----- .../PostgresOutboxOptionsScopeTests.cs | 99 ++++++++----------- ...PostgresOutboxRepeatedRegistrationTests.cs | 4 +- .../PostgresOutboxTransactionTests.cs | 70 +++++++++++++ website/content/docs/mocha/reliability.md | 4 +- 10 files changed, 155 insertions(+), 131 deletions(-) create mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs delete mode 100644 src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index e5199e5e0da..ad7de2b38d0 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -110,7 +110,15 @@ public async ValueTask PersistAsync(MessageEnvelope envelope, CancellationToken await command.ExecuteNonQueryAsync(cancellationToken); - if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is not NpgsqlTransaction) + if (_originalDbContext.Database.CurrentTransaction?.GetDbTransaction() is NpgsqlTransaction) + { + // A context without the messaging extension has no outbox state and no commit interceptor. + if (_originalDbContext.GetInfrastructure().GetService() is { } state) + { + state.HasUncommittedMessages = true; + } + } + else { _signal.SetAfterAmbientTransaction(); } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs new file mode 100644 index 00000000000..1426c665b66 --- /dev/null +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/DbContextOutboxState.cs @@ -0,0 +1,12 @@ +namespace Mocha.EntityFrameworkCore; + +/// +/// The outbox state of a single DbContext instance. +/// +internal sealed class DbContextOutboxState +{ + /// + /// Gets or sets whether the context wrote outbox messages in a transaction that has not committed yet. + /// + public bool HasUncommittedMessages { get; set; } +} diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs index c4f726b7e1e..3a66cae1069 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxDbTransactionInterceptor.cs @@ -1,11 +1,12 @@ using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; namespace Mocha.EntityFrameworkCore; /// -/// Intercepts Entity Framework Core database transaction commit events to signal the outbox processor -/// of the application that created the context. +/// Signals the outbox processor of a context when a transaction commits in which the context wrote +/// outbox messages. /// internal sealed class OutboxDbTransactionInterceptor : DbTransactionInterceptor { @@ -23,6 +24,17 @@ public override Task TransactionCommittedAsync( /// public override void TransactionCommitted(DbTransaction transaction, TransactionEndEventData eventData) { - eventData.Context?.GetMessagingServices().OutboxSignal?.Set(); + if (eventData.Context is not { } context) + { + return; + } + + var state = context.GetService(); + + if (state.HasUncommittedMessages) + { + state.HasUncommittedMessages = false; + context.GetMessagingServices().OutboxSignal?.Set(); + } } } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs index c734e847d3a..4c323cc834a 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -6,13 +6,13 @@ namespace Mocha.EntityFrameworkCore; /// /// Provides extension methods on for registering -/// core outbox interceptors that signal the outbox processor after save and transaction commit. +/// the core outbox services of a context. /// public static class OutboxEntityFrameworkCorePersistenceBuilderExtensions { /// - /// Registers the core outbox infrastructure, including EF Core interceptors that signal the - /// outbox processor when changes are saved or transactions are committed. + /// Registers the core outbox infrastructure of the context, including the EF Core interceptor that signals + /// the outbox processor when a transaction in which the context wrote outbox messages commits. /// /// The Entity Framework Core builder to configure. /// The same instance for chaining. @@ -31,8 +31,8 @@ public static IEntityFrameworkCoreBuilder UseOutboxCore(this IEntityFrameworkCor builder.ConfigureEntityFrameworkServices(static services => { + services.AddScoped(); services.AddSingleton(); - services.AddSingleton(); }); return builder; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs deleted file mode 100644 index db4c1f1990b..00000000000 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxSaveChangesInterceptor.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.EntityFrameworkCore.Diagnostics; - -namespace Mocha.EntityFrameworkCore; - -/// -/// Intercepts Entity Framework Core save changes events to signal the outbox processor -/// of the application that created the context. -/// -internal sealed class OutboxSaveChangesInterceptor : SaveChangesInterceptor -{ - /// - public override ValueTask SavedChangesAsync( - SaveChangesCompletedEventData eventData, - int result, - CancellationToken cancellationToken = default) - { - return new(SavedChanges(eventData, result)); - } - - /// - public override int SavedChanges(SaveChangesCompletedEventData eventData, int result) - { - if (eventData.Context is not { } context) - { - return result; - } - - if (context.Database.CurrentTransaction is null) - { - context.GetMessagingServices().OutboxSignal?.SetAfterAmbientTransaction(); - } - - return result; - } -} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs index 7828b2ef311..7756064fa9f 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using System.Text.Json; using System.Transactions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -67,31 +66,6 @@ public async Task PersistAsync_Should_SignalOnlyAfterCommit_When_ManyMessagesSha AssertSignaledOnlyAfterCommit(signal); } - [Fact] - public async Task SaveChanges_Should_SignalOnlyAfterCommit_When_AmbientTransactionIsUsed() - { - // arrange - var connectionString = await fixture.CreateDatabaseAsync(); - var signal = new VisibilityProbeSignal(connectionString); - await using var provider = await CreateProviderAsync(connectionString, signal, addHandler: false); - await EnsureCreatedAsync(provider); - signal.Events.Clear(); - - // act - using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) - { - await using var scope = provider.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - db.Add(new OutboxMessage(Guid.NewGuid(), JsonDocument.Parse("{}"))); - await db.SaveChangesAsync(TestToken); - signal.Mark("before-complete"); - transaction.Complete(); - } - - // assert - AssertSignaledOnlyAfterCommit(signal); - } - [Fact] public async Task PersistAsync_Should_SignalOnCompletion_When_AmbientTransactionRollsBack() { diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs index a631dde8df2..38ec3254aaf 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs @@ -3,8 +3,10 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; +using Mocha.Middlewares; using Mocha.Outbox; using Mocha.Scheduling; using Mocha.Transport.InMemory; @@ -18,69 +20,26 @@ public sealed class PostgresOutboxOptionsScopeTests(PostgresFixture fixture) : I private static CancellationToken TestToken => TestContext.Current.CancellationToken; - [Fact] - public async Task SaveChangesAsync_Should_SignalOutbox_When_ScopedFactoryOptionsScopeIsDisposed() + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task CommitAsync_Should_SignalOutbox_When_OptionsScopeIsDisposed(bool scopedFactory) { // arrange var connectionString = await CreateDatabaseAsync(); var signal = new StubOutboxSignal(); - await using var provider = await CreateOutboxProviderAsync( - connectionString, - ContextRegistration.ScopedFactory, - signal); - await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); - db.Orders.Add(new Order { Id = 2 }); - - // act - await db.SaveChangesAsync(TestToken); - - // assert - Assert.Equal(2, await CountOrdersAsync(connectionString)); - Assert.Equal(2, signal.SetCallCount); - } - - [Fact] - public async Task SaveChangesAsync_Should_SignalOutbox_When_ConstructorOptionsScopeIsDisposed() - { - // arrange - var connectionString = await CreateDatabaseAsync(); - var signal = new StubOutboxSignal(); - await using var provider = await CreateOutboxProviderAsync( - connectionString, - ContextRegistration.ScopedOptions, - signal); - await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedOptions); - db.Orders.Add(new Order { Id = 2 }); - - // act - await db.SaveChangesAsync(TestToken); - - // assert - Assert.Equal(2, await CountOrdersAsync(connectionString)); - Assert.Equal(2, signal.SetCallCount); - } - - [Fact] - public async Task CommitAsync_Should_SignalOutbox_When_OptionsScopeIsDisposed() - { - // arrange - var connectionString = await CreateDatabaseAsync(); - var signal = new StubOutboxSignal(); - await using var provider = await CreateOutboxProviderAsync( - connectionString, - ContextRegistration.ScopedFactory, - signal); - await using var db = await CreateContextOutlivingScopeAsync(provider, ContextRegistration.ScopedFactory); + var registration = scopedFactory ? ContextRegistration.ScopedFactory : ContextRegistration.ScopedOptions; + await using var provider = await CreateOutboxProviderAsync(connectionString, registration, signal); + await using var db = await CreateContextOutlivingScopeAsync(provider, registration); + using var outbox = CreateOutbox(provider, db); await using var transaction = await db.Database.BeginTransactionAsync(TestToken); - db.Orders.Add(new Order { Id = 2 }); - await db.SaveChangesAsync(TestToken); + await outbox.PersistAsync(CreateEnvelope(), TestToken); // act await transaction.CommitAsync(TestToken); // assert - Assert.Equal(2, await CountOrdersAsync(connectionString)); - Assert.Equal(2, signal.SetCallCount); + Assert.Equal(1, signal.SetCallCount); } [Fact] @@ -122,7 +81,7 @@ public async Task CommitAsync_Should_NotifyScheduler_When_OptionsScopeIsDisposed } [Fact] - public async Task SaveChangesAsync_Should_SignalOwnApplication_When_ApplicationsShareEntityFrameworkServices() + public async Task CommitAsync_Should_SignalOwnApplication_When_ApplicationsShareEntityFrameworkServices() { // arrange var connectionString = await CreateDatabaseAsync(); @@ -147,14 +106,16 @@ public async Task SaveChangesAsync_Should_SignalOwnApplication_When_Applications { await using var scope = providers[i].CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - db.Orders.Add(new Order { Id = i + 1 }); - await db.SaveChangesAsync(TestToken); + var bus = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + await bus.PublishAsync(new OrderPlaced(i + 1), TestToken); + await transaction.CommitAsync(TestToken); modelSources.Add(db.GetService()); } // assert Assert.Single(modelSources); - Assert.Equal([true, true, true], signals.Select(s => s.WasSet)); + Assert.Equal([1, 1, 1], signals.Select(s => s.SetCallCount)); } private async Task CreateDatabaseAsync() @@ -200,6 +161,30 @@ private static Task CreateOutboxProviderAsync( services => services.AddSingleton(signal), static ef => ef.UsePostgresOutbox()); + // The outbox gets a signal of its own, so that only the commit of the context reaches the application's signal. + private static PostgresMessageOutbox CreateOutbox(IServiceProvider provider, ScopeDbContext db) + { + var options = provider + .GetRequiredService>() + .Get(typeof(ScopeDbContext).FullName); + + return new PostgresMessageOutbox( + db, + new StubOutboxSignal(), + options.Queries.InsertEnvelope, + requireTransaction: true); + } + + private static MessageEnvelope CreateEnvelope() + => new() + { + MessageId = Guid.NewGuid().ToString(), + MessageType = "urn:message:order-placed", + DestinationAddress = "memory://test/queue", + SentAt = DateTimeOffset.UtcNow, + Body = "{\"orderId\":1}"u8.ToArray() + }; + private static Task CreateSchedulingProviderAsync( string connectionString, ISchedulerSignal signal) diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs index 74fa1fd98cf..06a5cb8e99e 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRepeatedRegistrationTests.cs @@ -32,9 +32,7 @@ public async Task UsePostgresOutbox_Should_RegisterEachInterceptorOnce_When_Call .Order(StringComparer.Ordinal); // assert - Assert.Equal( - ["OutboxDbTransactionInterceptor", "OutboxSaveChangesInterceptor"], - interceptors); + Assert.Equal(["OutboxDbTransactionInterceptor"], interceptors); } #endif diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs index b1146173e97..2b6d955cb0e 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs @@ -137,6 +137,76 @@ public async Task PublishAsync_Should_InsertRowWithTransaction_When_DatabaseTran Assert.Equal((0L, 1L), (rowsBeforeCommit, rowsAfterCommit)); } +#if NET9_0_OR_GREATER + [Fact] + public async Task CommitAsync_Should_SignalOnce_When_TransactionWroteMessages() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + await bus.PublishAsync(new OrderPlaced { OrderId = 2 }, TestToken); + var signalsBeforeCommit = signal.SetCallCount; + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal((0, 1), (signalsBeforeCommit, signal.SetCallCount)); + } + + [Fact] + public async Task CommitAsync_Should_NotSignal_When_TransactionWroteNoMessage() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal(0, signal.SetCallCount); + } + + [Fact] + public async Task CommitAsync_Should_NotSignalAgain_When_LaterTransactionWroteNoMessage() + { + // arrange + var connectionString = await fixture.CreateDatabaseAsync(); + var signal = new StubOutboxSignal(); + await using var provider = await CreateProviderAsync(connectionString, signal); + await EnsureCreatedAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var bus = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + await using (var first = await db.Database.BeginTransactionAsync(TestToken)) + { + await bus.PublishAsync(new OrderPlaced { OrderId = 1 }, TestToken); + await first.CommitAsync(TestToken); + } + + await using var second = await db.Database.BeginTransactionAsync(TestToken); + + // act + await second.CommitAsync(TestToken); + + // assert + Assert.Equal(1, signal.SetCallCount); + } +#endif + [Fact] public async Task PublishAsync_Should_InsertRowWithTransaction_When_AmbientTransactionIsActive() { diff --git a/website/content/docs/mocha/reliability.md b/website/content/docs/mocha/reliability.md index c52d1dc7c37..16f5ea55d0a 100644 --- a/website/content/docs/mocha/reliability.md +++ b/website/content/docs/mocha/reliability.md @@ -757,7 +757,7 @@ public class OrderPlacedHandler(AppDbContext dbContext, IMessageBus bus) } ``` -After the transaction commits, the outbox processor dispatches the new message to the transport. On .NET 9 and later, a save or commit through EF Core wakes the outbox processor at once. On .NET 8, after a commit made directly through an externally owned database transaction, and after the commit of a transaction enlisted with `Database.EnlistTransaction`, the outbox processor finds the message the next time it checks the database. +After the transaction commits, the outbox processor dispatches the new message to the transport. On .NET 9 and later, a commit through EF Core wakes the outbox processor at once. On .NET 8, after a commit made directly through an externally owned database transaction, and after the commit of a transaction enlisted with `Database.EnlistTransaction`, the outbox processor finds the message the next time it checks the database. Without a notification, the outbox processor waits up to ten seconds before checking the database for messages to send. Configure this wait with `UsePostgresOutbox(options => options.PollingInterval = TimeSpan.FromSeconds(1))`. @@ -827,7 +827,7 @@ builder.Services ## How the outbox processor works -The outbox processor is a background hosted service (`IHostedService`). When the EF Core interceptors detect a `SaveChanges` or transaction commit, they signal the processor through `IOutboxSignal`. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. +The outbox processor is a background hosted service (`IHostedService`). A transaction that wrote an outbox message signals it through `IOutboxSignal` when it commits through EF Core. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. Dispatch middleware runs once per message, when the message is written to the outbox. The processor does not run dispatch middleware again when it sends the stored envelope. From a39ec1549c33730197262d01a1823abeca5e272c Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:37:21 +0000 Subject: [PATCH 12/13] [Mocha] Give each outbox context its own outbox signal All outbox processors of an application waited on one IOutboxSignal, so a commit that wrote a message on one context woke the processor of every context. UseOutboxCore on the Entity Framework Core builder now registers a signal for its context, with the DbContext type as the service key, and the outbox and the processor of the context use it. MessagingDbContextServices is registered once per context type, so the commit interceptor signals the context that committed. --- .../OutboxServiceCollectionExtensions.cs | 2 +- .../Outbox/PostgresMessageOutbox.cs | 2 +- .../MessageBusHostBuilderExtensions.cs | 15 +++-- .../MessagingDbContextServices.cs | 8 +-- ...ameworkCorePersistenceBuilderExtensions.cs | 6 +- src/Mocha/src/Mocha.Outbox/Assembly.cs | 3 + .../PostgresMultipleContextOutboxTests.cs | 66 +++++++++++++++++-- ...gresOutboxAmbientTransactionSignalTests.cs | 2 +- .../PostgresOutboxExpirationTests.cs | 2 +- .../PostgresOutboxOptionsScopeTests.cs | 2 +- .../PostgresOutboxRelayClockTests.cs | 2 +- .../PostgresOutboxSleepLogTests.cs | 2 +- .../PostgresOutboxTransactionTests.cs | 2 +- .../PostgresOutboxUnresolvableMessageTests.cs | 4 +- website/content/docs/mocha/reliability.md | 2 +- 15 files changed, 92 insertions(+), 28 deletions(-) create mode 100644 src/Mocha/src/Mocha.Outbox/Assembly.cs diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs index 652dfff5a7f..a01a26481c9 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/OutboxServiceCollectionExtensions.cs @@ -90,7 +90,7 @@ public static IEntityFrameworkCoreBuilder UsePostgresOutbox( sp, sp.GetRequiredService(), sp.GetRequiredService(), - sp.GetRequiredService(), + sp.GetRequiredKeyedService(contextType), options); }); diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs index ad7de2b38d0..3450c029337 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore.Postgres/Outbox/PostgresMessageOutbox.cs @@ -56,7 +56,7 @@ public PostgresMessageOutbox( public static PostgresMessageOutbox Create(Type contextType, string optionsName, IServiceProvider services) { var dbContext = services.GetRequiredDbContext(contextType); - var signal = services.GetRequiredService(); + var signal = services.GetRequiredKeyedService(contextType); var outboxOptionsMonitor = services.GetRequiredService>(); var outboxOptions = outboxOptionsMonitor.Get(optionsName); var insertSql = outboxOptions.Queries.InsertEnvelope; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs index e4e31244d92..ac1d959e30b 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessageBusHostBuilderExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; using Mocha.Outbox; using Mocha.Scheduling; @@ -38,15 +39,19 @@ public static IMessageBusHostBuilder AddEntityFramework( builder.Services.AddOptions(efBuilder.Name); - builder.Services.TryAddSingleton(static services => new MessagingDbContextServices( - services.GetService(), - services.GetService(), - services.GetTimeProvider())); + builder.Services.TryAddKeyedSingleton( + typeof(TContext), + static (services, contextType) => new MessagingDbContextServices( + services.GetKeyedService(contextType), + services.GetService(), + services.GetTimeProvider())); builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton< IDbContextOptionsConfiguration, MessagingDbContextOptionsConfiguration - >()); + >(static services => new MessagingDbContextOptionsConfiguration( + services.GetRequiredService>(), + services.GetRequiredKeyedService(typeof(TContext))))); return builder; } diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs index b3796d5748d..f75fcf5c813 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/MessagingDbContextServices.cs @@ -4,10 +4,10 @@ namespace Mocha.EntityFrameworkCore; /// -/// The application singletons that the messaging interceptors and the outbox of a DbContext use. -/// A service provider has one instance, which identifies the application of a context. +/// The application singletons that the messaging interceptors and the outbox of a DbContext type use. +/// A service provider has one instance per context type, which identifies the application of a context. /// -/// The outbox signal of the application, or null when it has no outbox. +/// The outbox signal of the context type, or null when it has no outbox. /// The scheduler signal of the application, or null when it has no scheduler. /// The time provider of the application. internal sealed class MessagingDbContextServices( @@ -16,7 +16,7 @@ internal sealed class MessagingDbContextServices( TimeProvider timeProvider) { /// - /// Gets the outbox signal of the application, or null when the application has no outbox. + /// Gets the outbox signal of the context type, or null when the context type has no outbox. /// public IOutboxSignal? OutboxSignal { get; } = outboxSignal; diff --git a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs index 4c323cc834a..e2bc74c6835 100644 --- a/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs +++ b/src/Mocha/src/Mocha.EntityFrameworkCore/Outbox/OutboxEntityFrameworkCorePersistenceBuilderExtensions.cs @@ -1,5 +1,6 @@ using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Mocha.Outbox; namespace Mocha.EntityFrameworkCore; @@ -11,8 +12,8 @@ namespace Mocha.EntityFrameworkCore; public static class OutboxEntityFrameworkCorePersistenceBuilderExtensions { /// - /// Registers the core outbox infrastructure of the context, including the EF Core interceptor that signals - /// the outbox processor when a transaction in which the context wrote outbox messages commits. + /// Registers the core outbox infrastructure of the context: its outbox signal, and the EF Core interceptor + /// that raises the signal when a transaction in which the context wrote outbox messages commits. /// /// The Entity Framework Core builder to configure. /// The same instance for chaining. @@ -27,6 +28,7 @@ public static IEntityFrameworkCoreBuilder UseOutboxCore(this IEntityFrameworkCor } builder.Services.AddSingleton(new OutboxDbContextRegistration(builder.ContextType)); + builder.Services.TryAddKeyedSingleton(builder.ContextType); builder.HostBuilder.UseOutboxCore(); builder.ConfigureEntityFrameworkServices(static services => diff --git a/src/Mocha/src/Mocha.Outbox/Assembly.cs b/src/Mocha/src/Mocha.Outbox/Assembly.cs new file mode 100644 index 00000000000..27476eb262a --- /dev/null +++ b/src/Mocha/src/Mocha.Outbox/Assembly.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Mocha.EntityFrameworkCore")] diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs index a654522824c..6677784a166 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMultipleContextOutboxTests.cs @@ -17,7 +17,7 @@ public sealed class PostgresMultipleContextOutboxTests(PostgresFixture fixture) private static CancellationToken TestToken => TestContext.Current.CancellationToken; [Fact] - public async Task Set_Should_WakeEveryOutboxProcessor_When_MultipleContextsAreIdle() + public async Task Set_Should_WakeOnlyTheProcessorOfItsContext_When_MultipleContextsAreIdle() { // arrange var firstConnection = await fixture.CreateDatabaseAsync(); @@ -39,7 +39,8 @@ public async Task Set_Should_WakeEveryOutboxProcessor_When_MultipleContextsAreId await using var provider = await CreateProviderAsync(firstConnection, secondConnection, wakeOnlyOnSignal: true); var firstIdle = ObserveFirstPollCompletion(provider); var secondIdle = ObserveFirstPollCompletion(provider); - var signal = provider.GetRequiredService(); + var signal = provider.GetRequiredKeyedService(typeof(SecondDbContext)); + var recorder = provider.GetRequiredService(); var runtime = provider.GetRequiredService(); var type = runtime.GetMessageType(typeof(ContextEvent)); var endpoint = runtime.GetPublishEndpoint(type); @@ -66,11 +67,16 @@ public async Task Set_Should_WakeEveryOutboxProcessor_When_MultipleContextsAreId // act signal.Set(); - var recorder = provider.GetRequiredService(); - await recorder.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestToken); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + while (recorder.Messages.IsEmpty) + { + await Task.Delay(25, timeout.Token); + } // assert - Assert.Equal(["first", "second"], recorder.Messages.Order().ToArray()); + Assert.Equal(["second"], recorder.Messages.ToArray()); + Assert.Equal(1, await MessageRows.CountOutboxAsync(firstConnection, TestToken)); } finally { @@ -81,6 +87,48 @@ public async Task Set_Should_WakeEveryOutboxProcessor_When_MultipleContextsAreId } } +#if NET9_0_OR_GREATER + [Fact] + public async Task CommitAsync_Should_SignalOnlyItsContext_When_MultipleContextsAreRegistered() + { + // arrange + var firstConnection = await fixture.CreateDatabaseAsync(); + var secondConnection = await fixture.CreateDatabaseAsync(); + var firstSignal = new StubOutboxSignal(); + var secondSignal = new StubOutboxSignal(); + var services = new ServiceCollection(); + services.AddKeyedSingleton(typeof(FirstDbContext), firstSignal); + services.AddKeyedSingleton(typeof(SecondDbContext), secondSignal); + await using var provider = await CreateProviderAsync( + services, + firstConnection, + secondConnection, + wakeOnlyOnSignal: false); + await using var scope = provider.CreateAsyncScope(); + var second = scope.ServiceProvider.GetRequiredService(); + using var outbox = PostgresMessageOutbox.Create( + typeof(SecondDbContext), + typeof(SecondDbContext).FullName!, + scope.ServiceProvider); + await using var transaction = await second.Database.BeginTransactionAsync(TestToken); + await outbox.PersistAsync( + new MessageEnvelope + { + MessageId = Guid.NewGuid().ToString(), + MessageType = "urn:message:context-event", + DestinationAddress = "memory://test/queue", + Body = "{\"context\":\"second\"}"u8.ToArray() + }, + TestToken); + + // act + await transaction.CommitAsync(TestToken); + + // assert + Assert.Equal((0, 1), (firstSignal.SetCallCount, secondSignal.SetCallCount)); + } +#endif + [Fact] public async Task PublishAsync_Should_PersistToFirstRegisteredContext_When_MultipleContextsAreRegistered() { @@ -204,12 +252,18 @@ private static Task ObserveFirstPollCompletion(ServiceProvider provide // With wakeOnlyOnSignal the relays poll every 10 minutes and no consumer transaction commits, so only the // outbox signal wakes an idle relay. + private static Task CreateProviderAsync( + string firstConnection, + string secondConnection, + bool wakeOnlyOnSignal) + => CreateProviderAsync(new ServiceCollection(), firstConnection, secondConnection, wakeOnlyOnSignal); + private static async Task CreateProviderAsync( + ServiceCollection services, string firstConnection, string secondConnection, bool wakeOnlyOnSignal) { - var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(); services.AddDbContextFactory(options => options.UseTestNpgsql(firstConnection)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs index 7756064fa9f..8c7a4bc5ca6 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs @@ -177,7 +177,7 @@ private static async Task CreateProviderAsync( services.AddSingleton(recorder ?? new MessageRecorder()); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(signal); + services.AddKeyedSingleton(typeof(TestDbContext), signal); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs index b3abc21fe7c..bbf127689e5 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxExpirationTests.cs @@ -91,7 +91,7 @@ public async Task ProcessAsync_Should_DiscardExpiredMessage_When_DeadlinePassesA // the failed delivery is made due at once instead of after the retry delay await MessageRows.WaitForOutboxTimesSentAsync(connectionString, id, 1, s_timeout, TestToken); await MessageRows.MakeOutboxDueAsync(connectionString, TestToken); - provider.GetRequiredService().Set(); + provider.GetRequiredKeyedService(typeof(TestDbContext)).Set(); var remainingAttempts = await MessageRows.WaitForOutboxRetryAsync( connectionString, id, s_timeout, TestToken); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs index 38ec3254aaf..82106c3e641 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxOptionsScopeTests.cs @@ -158,7 +158,7 @@ private static Task CreateOutboxProviderAsync( => CreateProviderAsync( connectionString, registration, - services => services.AddSingleton(signal), + services => services.AddKeyedSingleton(typeof(ScopeDbContext), signal), static ef => ef.UsePostgresOutbox()); // The outbox gets a signal of its own, so that only the commit of the context reaches the application's signal. diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs index f356ebbef6e..9b263e9cb1c 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxRelayClockTests.cs @@ -101,7 +101,7 @@ private static async Task CreateProviderAsync( { var services = new ServiceCollection(); services.AddSingleton(new FakeTimeProvider(s_now)); - services.AddSingleton(); + services.AddKeyedSingleton(typeof(TestDbContext)); services.AddSingleton(recorder); services.AddDbContext(options => options.UseTestNpgsql(connectionString)); var builder = services.AddMessageBus(); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs index fe60873c429..ff9f7621000 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxSleepLogTests.cs @@ -98,7 +98,7 @@ private static async Task CreateProviderAsync( var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton>(logger); - services.AddSingleton(); + services.AddKeyedSingleton(typeof(TestDbContext)); services.AddDbContext(options => options.UseTestNpgsql(connectionString)); var builder = services.AddMessageBus(); builder.AddEntityFramework( diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs index 2b6d955cb0e..122817825ba 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxTransactionTests.cs @@ -322,7 +322,7 @@ private static async Task CreateProviderAsync( { var services = new ServiceCollection(); services.AddLogging(); - services.AddSingleton(signal); + services.AddKeyedSingleton(typeof(TransactionDbContext), signal); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); var builder = services.AddMessageBus(); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs index 5e9cffe4d14..9015f09a470 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxUnresolvableMessageTests.cs @@ -32,7 +32,7 @@ public async Task Outbox_Should_RetryMessage_When_MessageTypeIsUnknown() TestContext.Current.CancellationToken); // act - host.Services.GetRequiredService().Set(); + host.Services.GetRequiredKeyedService(typeof(TestDbContext)).Set(); // assert var timesSent = await MessageRows.WaitForOutboxTimesSentAsync( @@ -66,7 +66,7 @@ public async Task Outbox_Should_RetryMessage_When_DestinationIsUnresolvable() TestContext.Current.CancellationToken); // act - host.Services.GetRequiredService().Set(); + host.Services.GetRequiredKeyedService(typeof(TestDbContext)).Set(); // assert var timesSent = await MessageRows.WaitForOutboxTimesSentAsync( diff --git a/website/content/docs/mocha/reliability.md b/website/content/docs/mocha/reliability.md index 16f5ea55d0a..41984438f75 100644 --- a/website/content/docs/mocha/reliability.md +++ b/website/content/docs/mocha/reliability.md @@ -827,7 +827,7 @@ builder.Services ## How the outbox processor works -The outbox processor is a background hosted service (`IHostedService`). A transaction that wrote an outbox message signals it through `IOutboxSignal` when it commits through EF Core. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. +The outbox processor is a background hosted service (`IHostedService`). Each outbox context has its own processor and its own `IOutboxSignal`. A transaction that wrote an outbox message signals the processor of its context when it commits through EF Core. Inside an ambient `TransactionScope`, the signal is raised when the ambient transaction completes. The processor reads pending `OutboxMessage` rows, deserializes the envelope, and sends each message directly to the transport. Dispatch middleware runs once per message, when the message is written to the outbox. The processor does not run dispatch middleware again when it sends the stored envelope. From 57c54d37be818acd05216e4f1b63879298c28c24 Mon Sep 17 00:00:00 2001 From: tobias-tengler <45513122+tobias-tengler@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:37:29 +0000 Subject: [PATCH 13/13] [Mocha] Remove the resilient outbox signal from the Postgres outbox tests The tests replaced the outbox signal with ResilientOutboxSignal, because an interceptor could signal the disposed signal of another service provider. The interceptors now read the signal of the application that created the context, so the tests run with the signal that the outbox registers and the helper is removed. --- .../Helpers/ResilientOutboxSignal.cs | 78 ------------------- .../InboxServiceRegistrationTests.cs | 6 -- .../OutboxServiceRegistrationTests.cs | 1 - .../PostgresMessageOutboxTests.cs | 1 - ...gresOutboxAmbientTransactionSignalTests.cs | 9 ++- .../PostgresOutboxIntegrationTests.cs | 8 -- 6 files changed, 6 insertions(+), 97 deletions(-) delete mode 100644 src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs deleted file mode 100644 index 63ae700df2f..00000000000 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/Helpers/ResilientOutboxSignal.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Mocha.Outbox; - -namespace Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; - -/// -/// An outbox signal whose never throws -/// . The production -/// MessageBusOutboxSignal wraps AsyncAutoResetEvent which -/// throws on Set() after disposal. In integration tests the outbox -/// processor's own transaction commits fire the EF Core interceptor that -/// calls Set(), and this can race with provider disposal. -/// -/// Uses a TaskCompletionSource to implement auto-reset semantics. -/// Unlike SemaphoreSlim, this approach does not accumulate waiters -/// across loop iterations - each WaitAsync atomically exchanges -/// the TCS, and Set signals whoever is currently waiting. -/// -/// -internal sealed class ResilientOutboxSignal : IOutboxSignal -{ -#if NET9_0_OR_GREATER - private readonly Lock _lock = new(); -#else - private readonly object _lock = new(); -#endif - private TaskCompletionSource _tcs; - - public ResilientOutboxSignal() - { - // Start signaled (like production AsyncAutoResetEvent(true)) - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _tcs.TrySetResult(); - } - - public void Set() - { - lock (_lock) - { - if (!_tcs.TrySetResult()) - { - // TCS was already cancelled or faulted - replace with a - // pre-completed TCS so the next WaitAsync sees the signal. - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - _tcs.TrySetResult(); - } - } - } - - public Task WaitAsync(CancellationToken cancellationToken) - { - lock (_lock) - { - var task = _tcs.Task; - - if (task.IsCompletedSuccessfully) - { - // Reset: replace with a new, unsignaled TCS - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - return Task.CompletedTask; - } - - if (task.IsCanceled || task.IsFaulted) - { - // Previous waiter was cancelled - replace with fresh TCS - _tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - } - - // Register cancellation on the current TCS - var tcs = _tcs; - if (cancellationToken.CanBeCanceled) - { - cancellationToken.Register(static state => ((TaskCompletionSource)state!).TrySetCanceled(), tcs); - } - - return tcs.Task; - } - } -} diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs index baabe262685..ff64c6dcc80 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/InboxServiceRegistrationTests.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Options; using Mocha.EntityFrameworkCore.Postgres.Tests.Helpers; using Mocha.Inbox; -using Mocha.Outbox; using Mocha.Transport.InMemory; namespace Mocha.EntityFrameworkCore.Postgres.Tests; @@ -113,11 +112,6 @@ private static ServiceProvider BuildProvider(Action? configure = n services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); - // Use a resilient signal to prevent ObjectDisposedException when - // EF Core shares the internal service provider (and interceptors) - // across test classes via ShouldUseSameServiceProvider. - services.AddSingleton(); - var builder = services.AddMessageBus(); builder.AddEntityFramework( ef => ef.UsePostgresInbox(configure)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs index cf1ec4e4cf5..67c6d14a960 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/OutboxServiceRegistrationTests.cs @@ -180,7 +180,6 @@ private static ServiceCollection CreateServices() var services = new ServiceCollection(); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(ConnectionString)); - services.AddSingleton(); return services; } diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs index 07358e8fc9a..1e323851afa 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresMessageOutboxTests.cs @@ -23,7 +23,6 @@ public async Task PersistAsync_Should_UseNamedOptions_When_TransactionRequiremen var connectionString = await _fixture.CreateDatabaseAsync(); var services = new ServiceCollection(); services.AddDbContext(options => options.UseTestNpgsql(connectionString)); - services.AddSingleton(); services.AddMessageBus().AddEntityFramework(ef => ef.UsePostgresOutbox()); services.PostConfigure( typeof(TestDbContext).FullName, diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs index 8c7a4bc5ca6..38480e20b13 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxAmbientTransactionSignalTests.cs @@ -101,7 +101,7 @@ public async Task Worker_Should_DeliverMessage_When_PublishedInsideAmbientTransa var recorder = new MessageRecorder(); await using var provider = await CreateProviderAsync( connectionString, - new ResilientOutboxSignal(), + signal: null, addHandler: true, recorder); await EnsureCreatedAsync(provider); @@ -169,7 +169,7 @@ private static async Task EnsureCreatedAsync(IServiceProvider provider) private static async Task CreateProviderAsync( string connectionString, - IOutboxSignal signal, + IOutboxSignal? signal, bool addHandler, MessageRecorder? recorder = null) { @@ -177,7 +177,10 @@ private static async Task CreateProviderAsync( services.AddSingleton(recorder ?? new MessageRecorder()); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddKeyedSingleton(typeof(TestDbContext), signal); + if (signal is not null) + { + services.AddKeyedSingleton(typeof(TestDbContext), signal); + } var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); diff --git a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs index 0fc506d8357..dbcd2657767 100644 --- a/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs +++ b/src/Mocha/test/Mocha.EntityFrameworkCore.Postgres.Tests/PostgresOutboxIntegrationTests.cs @@ -153,7 +153,6 @@ public async Task Outbox_Should_ProcessPendingMessages_When_WorkerStartsAfterPer services.AddSingleton(recorder); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); @@ -229,7 +228,6 @@ public async Task Outbox_Should_ResumeProcessing_When_WorkerRestartedAfterInterr services.AddSingleton(recorder); services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - services.AddSingleton(); var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); @@ -459,12 +457,6 @@ private async Task CreateBusWithOutboxAsync( services.AddLogging(); services.AddDbContext(o => o.UseTestNpgsql(connectionString)); - // Register the resilient signal BEFORE UsePostgresOutbox() so that - // TryAddSingleton in AddOutboxCore() is a no-op. - // This prevents ObjectDisposedException during teardown when the - // outbox processor's own transaction commits fire the interceptor. - services.AddSingleton(); - var builder = services.AddMessageBus(); builder.AddEntityFramework(ef => ef.UsePostgresOutbox(o => o.RequireTransaction = false)); configureBus(builder);