1+ using System ;
2+ using System . Text . Json ;
3+ using System . Threading ;
4+ using System . Threading . Tasks ;
5+ using System . Timers ;
6+ using Microsoft . Extensions . Configuration ;
7+ using Microsoft . Extensions . Hosting ;
8+ using Microsoft . Extensions . Logging ;
9+ using Microsoft . Extensions . Options ;
10+ using Microsoft . FeatureManagement ;
11+ using Stravaig . Configuration . Diagnostics . Logging ;
12+ using Timer = System . Timers . Timer ;
13+
14+
15+ namespace Example ;
16+
17+ public class TheHostedService : IHostedService , IDisposable
18+ {
19+ private readonly ILogger < TheHostedService > _logger ;
20+ private readonly IConfigurationRoot _configRoot ;
21+ private readonly IFeatureManager _featureManager ;
22+ private readonly IOptionsMonitor < MyFeatureConfiguration > _featureValues ;
23+ private readonly Timer _timer ;
24+
25+ public TheHostedService (
26+ ILogger < TheHostedService > logger ,
27+ IConfigurationRoot configRoot ,
28+ IFeatureManager featureManager ,
29+ IOptionsMonitor < MyFeatureConfiguration > featureValues )
30+ {
31+ _logger = logger ;
32+ _configRoot = configRoot ;
33+ _featureManager = featureManager ;
34+ _featureValues = featureValues ;
35+ _timer = new Timer ( 10000 ) ;
36+ _timer . Elapsed += TimerOnElapsed ;
37+ featureValues . OnChange ( ( _ , s ) =>
38+ {
39+ Console . WriteLine ( $ "[{ DateTime . Now : HH:mm:ss} ] Change Detected. { s } ") ;
40+ } ) ;
41+ }
42+
43+ private async void TimerOnElapsed ( object ? sender , ElapsedEventArgs e )
44+ {
45+ var jsonOptions = new JsonSerializerOptions ( )
46+ {
47+ WriteIndented = true ,
48+ } ;
49+ string json = JsonSerializer . Serialize ( _featureValues . CurrentValue , jsonOptions ) ;
50+ Console . Clear ( ) ;
51+ _logger . LogInformation (
52+ "At {Time} the object looks like:\n {Json}" ,
53+ e . SignalTime ,
54+ json ) ;
55+ await foreach ( string feature in _featureManager . GetFeatureNamesAsync ( ) )
56+ {
57+ var state = await _featureManager . IsEnabledAsync ( feature ) ;
58+ _logger . LogInformation ( "{Feature} : {State}" , feature , state ) ;
59+ }
60+ _logger . LogConfigurationValuesAsInformation ( _configRoot . GetSection ( "MyConfiguration" ) ) ;
61+ }
62+
63+ public Task StartAsync ( CancellationToken cancellationToken )
64+ {
65+ _logger . LogInformation ( "The hosted service is starting." ) ;
66+ _logger . LogProvidersAsInformation ( _configRoot ) ;
67+ _timer . Enabled = true ;
68+ return Task . CompletedTask ;
69+ }
70+
71+ public Task StopAsync ( CancellationToken cancellationToken )
72+ {
73+ _timer . Enabled = false ;
74+ _logger . LogInformation ( "The hosted service is ending." ) ;
75+ return Task . CompletedTask ;
76+ }
77+
78+ public void Dispose ( )
79+ {
80+ _timer . Dispose ( ) ;
81+ }
82+ }
0 commit comments