1
1
using System ;
2
+ using System . Linq ;
2
3
using System . Threading ;
3
4
using System . Threading . Tasks ;
4
5
using Microsoft . Extensions . Hosting ;
5
6
using Microsoft . Extensions . Logging ;
7
+ using Microsoft . Extensions . Options ;
6
8
7
9
namespace LongRunningConsole . Services
8
10
{
@@ -21,15 +23,26 @@ public class MyService : IHostedService, IDisposable
21
23
/// </summary>
22
24
private Timer timer ;
23
25
26
+ private readonly IOptions < AppConfig > _appConfig ;
27
+
28
+ private readonly ServiceConfig serviceConfig ;
29
+
24
30
/// <summary>
25
31
/// Initializes a new instance of the <see cref="MyService"/> class.
26
32
/// </summary>
27
33
/// <param name="logger">
28
34
/// The logger.
29
35
/// </param>
30
- public MyService ( ILogger < MyService > logger )
36
+ public MyService ( ILogger < MyService > logger , IOptions < AppConfig > appConfig )
31
37
{
32
38
this . logger = logger ?? throw new ArgumentNullException ( nameof ( logger ) ) ;
39
+ this . _appConfig = appConfig ?? throw new ArgumentNullException ( nameof ( appConfig ) ) ;
40
+
41
+ serviceConfig = this . _appConfig . Value . Services . OfType < ServiceConfig > ( ) . FirstOrDefault ( s => s . ServiceName . Equals ( nameof ( MyService ) ) ) ;
42
+
43
+ if ( serviceConfig is null ) {
44
+ throw new ApplicationException ( $ "{ nameof ( serviceConfig ) } cannot be null.") ;
45
+ }
33
46
}
34
47
35
48
/// <summary>
@@ -44,7 +57,7 @@ public MyService(ILogger<MyService> logger)
44
57
public Task StartAsync ( CancellationToken cancellationToken )
45
58
{
46
59
Console . WriteLine ( $ "[{ DateTime . Now } ] { nameof ( MyService ) } background Service is starting.") ;
47
- this . timer = new Timer ( this . DoWork , null , TimeSpan . Zero , TimeSpan . FromSeconds ( 5 ) ) ;
60
+ this . timer = new Timer ( this . DoWork , null , TimeSpan . Zero , TimeSpan . FromSeconds ( serviceConfig . Frequency ) ) ;
48
61
return Task . CompletedTask ;
49
62
}
50
63
0 commit comments