77using HangFire . TopicExtensions . Interfaces ;
88using Microsoft . Extensions . DependencyInjection ;
99
10-
1110namespace HangFire . TopicExtensions
1211{
1312 public class TopicPublisher : ITopicPublisher
1413 {
15-
1614 private readonly IServiceProvider _serviceProvider ;
1715
1816 public TopicPublisher ( IServiceProvider serviceProvider )
1917 {
2018 _serviceProvider = serviceProvider ;
19+ BuildSubscribers ( ) ;
2120 }
2221
22+ public List < Subscription > Subscriptions { get ; set ; }
23+
2324 public void EnqueueTopic ( string topic , object context = null )
2425 {
25-
2626 // Find Subscribers
2727 BackgroundJob . Enqueue ( ( ) => DispatchTopic ( topic , context ) ) ;
28-
2928 }
3029
31- public void DispatchTopic ( string topic , object context )
30+ private void BuildSubscribers ( )
3231 {
32+ var allTypes = GetImplementationsOf < ISubscriber > ( ) ;
33+ Subscriptions = new List < Subscription > ( ) ;
3334
34- var allSubscribers = GetImplementationsOf < ISubscriber > ( ) ;
35-
36- foreach ( var type in allSubscribers )
35+ foreach ( var type in allTypes )
3736 {
38-
3937 var attributes = type . GetCustomAttributes < SubscriberJobAttribute > ( ) ;
4038
41- var subscribed = attributes . Any ( a => a . Topic . ToLower ( ) == topic ) ;
42- if ( ! subscribed ) continue ;
43-
44- var impl = ( ISubscriber ) ActivatorUtilities . CreateInstance ( _serviceProvider , type ) ;
45- BackgroundJob . Enqueue ( ( ) => impl . Execute ( context ) ) ;
39+ var subscriberJobAttributes = attributes . ToList ( ) ;
40+ if ( ! subscriberJobAttributes . Any ( ) ) continue ;
41+
42+
43+ var impl = ( ISubscriber ) ActivatorUtilities . CreateInstance ( _serviceProvider , type ) ;
4644
45+ foreach ( var subscriberJobAttribute in subscriberJobAttributes )
46+ {
47+ var subscription = new Subscription
48+ {
49+ Topic = subscriberJobAttribute . Topic ,
50+ Subscriber = impl
51+ } ;
52+
53+ Subscriptions . Add ( subscription ) ;
54+ }
4755 }
56+ }
4857
58+ public void DispatchTopic ( string topic , object context )
59+ {
60+ foreach ( var subscription in Subscriptions . Where ( s => s . Topic == topic ) )
61+ BackgroundJob . Enqueue ( ( ) => subscription . Subscriber . Execute ( context ) ) ;
4962 }
5063
5164 private static IEnumerable < Type > GetImplementationsOf < TInterface > ( )
@@ -56,7 +69,11 @@ private static IEnumerable<Type> GetImplementationsOf<TInterface>()
5669 assembly . GetTypes ( ) . Where ( type => ! type . IsInterface && interfaceType . IsAssignableFrom ( type ) ) )
5770 . SelectMany ( implementation => implementation ) ;
5871 }
59- }
60-
6172
73+ public class Subscription
74+ {
75+ public string Topic { get ; set ; }
76+ public ISubscriber Subscriber { get ; set ; }
77+ }
78+ }
6279}
0 commit comments