//-----------------------------------------------------------------------
//
// Copyright (c) lanedirt. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
//
//-----------------------------------------------------------------------
namespace AliasVault.WorkerStatus.ServiceExtensions;
using AliasVault.WorkerStatus.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
///
/// ServiceCollectionExtensions class.
///
public static class ServiceCollectionExtensions
{
///
/// Add a HostedService that is monitored by the StatusWorker.
///
/// IServiceCollection.
/// Worker type to add.
/// DBContext type to use for persisting and retrieving the status data.
/// The unique service name through which the worker processes
/// can be triggered to start or stop.
/// IServiceCollection instance.
public static IServiceCollection AddStatusHostedService(this IServiceCollection services, string serviceName)
where TWorker : class, IHostedService
where TContext : DbContext, IWorkerStatusDbContext
{
services.TryAddSingleton();
services.TryAddEnumerable(ServiceDescriptor.Singleton>());
// Only add these required helper services if they are not already registered.
services.TryAddEnumerable(ServiceDescriptor.Singleton());
services.TryAddSingleton(new GlobalServiceStatus(serviceName));
// Register the DbContext factory
services.TryAddSingleton>(sp =>
{
var factory = sp.GetRequiredService>();
return () => factory.CreateDbContext();
});
// Set HostOptions to ignore background service exceptions as we are handling them in the StatusWorker.
services.Configure(options =>
{
options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
});
return services;
}
}