33using Cnblogs . Architecture . Ddd . EventBus . Dapr ;
44using Microsoft . AspNetCore . Builder ;
55using Microsoft . Extensions . DependencyInjection ;
6+ using Microsoft . Extensions . Options ;
67
78// ReSharper disable once CheckNamespace
89namespace Microsoft . AspNetCore . Routing ;
@@ -62,14 +63,9 @@ public static IEndpointConventionBuilder Subscribe<TEvent>(
6263 string appName )
6364 where TEvent : IntegrationEvent
6465 {
65- EnsureDaprSubscribeHandlerMapped ( builder ) ;
66-
67- var serviceCheck = builder . ServiceProvider . GetRequiredService < IServiceProviderIsService > ( ) ;
68- if ( ! serviceCheck . IsService ( typeof ( IEventBus ) ) )
69- {
70- throw new InvalidOperationException (
71- $ "{ nameof ( IEventBus ) } has not been registered. Did you forget to call IServiceCollection.AddDaprEventBus()?") ;
72- }
66+ var daprOptions = builder . ServiceProvider . GetRequiredService < IOptions < DaprOptions > > ( ) . Value ;
67+ EnsureDaprSubscribeHandlerMapped ( builder , daprOptions ) ;
68+ EnsureEventBusRegistered ( builder , daprOptions ) ;
7369
7470 var result = builder
7571 . MapPost ( route , ( TEvent receivedEvent , IEventBus eventBus ) => eventBus . ReceiveAsync ( receivedEvent ) )
@@ -104,9 +100,26 @@ public static void Subscribe(this IEndpointRouteBuilder builder, params Assembly
104100 }
105101 }
106102
107- private static void EnsureDaprSubscribeHandlerMapped ( IEndpointRouteBuilder builder )
103+ private static void EnsureEventBusRegistered ( IEndpointRouteBuilder builder , DaprOptions daprOptions )
104+ {
105+ if ( daprOptions . IsEventBusRegistered )
106+ {
107+ return ;
108+ }
109+
110+ var serviceCheck = builder . ServiceProvider . GetRequiredService < IServiceProviderIsService > ( ) ;
111+ if ( ! serviceCheck . IsService ( typeof ( IEventBus ) ) )
112+ {
113+ throw new InvalidOperationException (
114+ $ "{ nameof ( IEventBus ) } has not been registered. Did you forget to call IServiceCollection.AddDaprEventBus()?") ;
115+ }
116+
117+ daprOptions . IsEventBusRegistered = true ;
118+ }
119+
120+ private static void EnsureDaprSubscribeHandlerMapped ( IEndpointRouteBuilder builder , DaprOptions daprOptions )
108121 {
109- if ( DaprOptions . IsDaprSubscribeHandlerMapped )
122+ if ( daprOptions . IsDaprSubscribeHandlerMapped )
110123 {
111124 return ;
112125 }
@@ -117,6 +130,6 @@ private static void EnsureDaprSubscribeHandlerMapped(IEndpointRouteBuilder build
117130 }
118131
119132 builder . MapSubscribeHandler ( ) ;
120- DaprOptions . IsDaprSubscribeHandlerMapped = true ;
133+ daprOptions . IsDaprSubscribeHandlerMapped = true ;
121134 }
122135}
0 commit comments