|
| 1 | +using System.Threading; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using CometD.NetCore.Salesforce; |
| 4 | +using KDCLLC.BuildingBlocks.Abstractions; |
| 5 | +using Microsoft.Extensions.Hosting; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using TestApp.EventBus.Messages; |
| 8 | + |
| 9 | +namespace TestApp.Services |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Provides with LifetimeEventsHostedService |
| 13 | + /// </summary> |
| 14 | + internal class SalesforceEventBusHostedService : IHostedService |
| 15 | + { |
| 16 | + private readonly ILogger _logger; |
| 17 | + private readonly IApplicationLifetime _appLifetime; |
| 18 | + private readonly SalesforceConfiguration _options; |
| 19 | + private readonly IEventBus _eventBus; |
| 20 | + |
| 21 | + public SalesforceEventBusHostedService( |
| 22 | + ILogger<SalesforceEventBusHostedService> logger, |
| 23 | + IApplicationLifetime appLifetime, |
| 24 | + SalesforceConfiguration options, |
| 25 | + IEventBus eventBus) |
| 26 | + { |
| 27 | + _logger = logger; |
| 28 | + _appLifetime = appLifetime; |
| 29 | + _options = options; |
| 30 | + _eventBus = eventBus; |
| 31 | + } |
| 32 | + |
| 33 | + public async Task StartAsync(CancellationToken cancellationToken) |
| 34 | + { |
| 35 | + _appLifetime.ApplicationStarted.Register(OnStarted); |
| 36 | + _appLifetime.ApplicationStopping.Register(OnStopping); |
| 37 | + _appLifetime.ApplicationStopped.Register(OnStopped); |
| 38 | + |
| 39 | + _logger.LogInformation("StartAsync has been called."); |
| 40 | + |
| 41 | + await _eventBus.Subscribe<CustomMessageListener>( |
| 42 | + new PlatformEvent() { Name = _options.CustomEvent, ReplayId= _options.ReplayId }); |
| 43 | + |
| 44 | + //return Task.CompletedTask; |
| 45 | + } |
| 46 | + |
| 47 | + public async Task StopAsync(CancellationToken cancellationToken) |
| 48 | + { |
| 49 | + _logger.LogInformation("StopAsync has been called."); |
| 50 | + |
| 51 | + await _eventBus.Unsubscribe<CustomMessageListener>( |
| 52 | + new PlatformEvent() { Name = _options.CustomEvent, ReplayId=_options.ReplayId}); |
| 53 | + } |
| 54 | + |
| 55 | + private void OnStarted() |
| 56 | + { |
| 57 | + _logger.LogInformation("OnStarted has been called."); |
| 58 | + |
| 59 | + // Perform post-startup activities here |
| 60 | + } |
| 61 | + |
| 62 | + private void OnStopping() |
| 63 | + { |
| 64 | + _logger.LogInformation("OnStopping has been called."); |
| 65 | + |
| 66 | + // Perform on-stopping activities here |
| 67 | + } |
| 68 | + |
| 69 | + private void OnStopped() |
| 70 | + { |
| 71 | + _logger.LogInformation("OnStopped has been called."); |
| 72 | + |
| 73 | + // Perform post-stopped activities here |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments