@@ -148,20 +148,19 @@ public async Task PublishAsync<TNotification>(
148148 var behaviors = _serviceProvider . GetServices < INotificationPipelineBehavior < TNotification > > ( ) ;
149149
150150 // Materialize behaviors once since we need to iterate multiple times
151- // Use stackalloc-friendly pattern for small counts
152151 var behaviorList = behaviors as INotificationPipelineBehavior < TNotification > [ ] ?? behaviors . ToArray ( ) ;
153152 Array . Reverse ( behaviorList ) ;
154153
155- // Count handlers to pre-allocate task array
154+ // Count handlers to pre-allocate delegate list
156155 var handlerList = handlers as INotificationHandler < TNotification > [ ] ?? handlers . ToArray ( ) ;
157156 if ( handlerList . Length == 0 )
158157 return ;
159158
160- var tasks = new Task [ handlerList . Length ] ;
159+ // Build a pipeline delegate for each handler
160+ var handlerDelegates = new Func < Task > [ handlerList . Length ] ;
161161 for ( int i = 0 ; i < handlerList . Length ; i ++ )
162162 {
163163 var handler = handlerList [ i ] ;
164- // Build the pipeline for this specific handler
165164 NotificationHandlerDelegate handlerDelegate = ( ) => handler . Handle ( notification , cancellationToken ) ;
166165
167166 // Wrap the handler with all behaviors (already reversed)
@@ -172,10 +171,21 @@ public async Task PublishAsync<TNotification>(
172171 handlerDelegate = ( ) => currentBehavior . Handle ( notification , currentDelegate , cancellationToken ) ;
173172 }
174173
175- tasks [ i ] = handlerDelegate ( ) ;
174+ var finalDelegate = handlerDelegate ;
175+ handlerDelegates [ i ] = ( ) => finalDelegate ( ) ;
176176 }
177177
178- await Task . WhenAll ( tasks ) ;
178+ // Delegate to the publish strategy
179+ var strategy = _serviceProvider . GetService < INotificationPublishStrategy > ( ) ;
180+ if ( strategy != null )
181+ {
182+ await strategy . PublishAsync ( handlerDelegates , cancellationToken ) ;
183+ }
184+ else
185+ {
186+ // Fallback to parallel when no strategy is registered (e.g., manual DI without AddCortexMediator)
187+ await Task . WhenAll ( handlerDelegates . Select ( d => d ( ) ) ) ;
188+ }
179189 }
180190
181191 public Task PublishAsync ( INotification notification , CancellationToken cancellationToken = default )
0 commit comments