Inital work on breaking out the core logic out of the MVC API Web App in preparation to migrating to minimal API's in a seperate project
This commit is contained in:
53
AS1024.GeoFeed.Core/GeoFeedPreloader/PreloadGeoFeed.cs
Normal file
53
AS1024.GeoFeed.Core/GeoFeedPreloader/PreloadGeoFeed.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using AS1024.GeoFeed.Core.Interfaces;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AS1024.GeoFeed.Core.GeoFeedPreloader
|
||||
{
|
||||
public class PreLoadGeoFeed : IHostedService
|
||||
{
|
||||
private readonly ILogger<PreLoadGeoFeed> logger;
|
||||
private readonly IGeoFeedProvider provider;
|
||||
private readonly IMemoryCache memoryCache;
|
||||
private readonly IHostEnvironment environment;
|
||||
private const string GeoFeedCacheKey = "GeoFeedData";
|
||||
|
||||
public PreLoadGeoFeed(ILogger<PreLoadGeoFeed> logger,
|
||||
IGeoFeedProvider provider,
|
||||
IMemoryCache memoryCache,
|
||||
IHostEnvironment environment)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.provider = provider;
|
||||
this.memoryCache = memoryCache;
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (environment.IsProduction())
|
||||
await StartPreLoad();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning($"Failed to preload, exception settings below:\n{ex}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StartPreLoad()
|
||||
{
|
||||
logger.LogInformation("Preloading GeoFeed data in memory...");
|
||||
List<Models.IPGeoFeed> feed = await provider.GetGeoFeedData();
|
||||
MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(45));
|
||||
memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions);
|
||||
}
|
||||
|
||||
Task IHostedService.StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user