I have written a .net core 3 workerservice which also has a webapi built into the same project - the purpose is to enable the hosted workerservice to present a healthcheck webapi which can be interrogated to provide the worker service status information. We use a common pattern to add healthcheck calls to all our webapi microservices.
The workerservice and webapi both work fine in themselves but I cannot work out how to inject a common object into the two services to be used to pass the data back and forth between the two.
I presume that I have to create the status object in the CreateHostBuilder method of the Program class and inject it into both but cannot find any suitable methods to pass it.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
// HealthCheck WebAPI
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel();
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseIISIntegration();
webBuilder.UseStartup<Startup>();
})
.ConfigureHostConfiguration(configHost =>
{
configHost.SetBasePath(Directory.GetCurrentDirectory());
configHost.AddJsonFile("hosting.json", optional: false);
})
// WorkerService
.ConfigureAppConfiguration((hostContext, config) =>
{
config
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName.ToLower()}.json", optional: false);
config.AddEnvironmentVariables();
})
.ConfigureServices((hostContext, services) =>
{
services.AddOptions();
services.AddHostedService<Worker>();
});
The status object could be something like...
public class StatusInfo
{
public DateTime LastRun { get; set; }
public int LastAdded { get; set; }
public int LastUpdated { get; set; }
}
Anyone help me out here, please?