I need to create a new host as a background service of a larger ASP.NET core application. This new background service can be created with a reference to the IServiceCollection of the larger host application which I store in a private field of my background service instance.
public class BackgroundWebHost : BackgroundService
{
private readonly IServiceCollection _services;
public BackgroundWebHost (IServiceCollection services)
{
_services = services;
}
I then have this private method to create the host which is then started asynchronously in the ExecuteAsync method of my background service.
private IHost CreateHost(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.ListenAnyIP(4999, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
webBuilder.UseStartup<Startup>();
})
.Build();
}
The Startup used contains application configuration but additional services can be registered into the larger application's DI container using an exposed API of the larger host application.
This process works great to get port 4999 open and accepting Http2 connections. However, I want to use dependencies registered in the larger host application, which are registered in the IServiceCollection _services of my background service. I tried looping through them and adding each service into the container created by the background service's host but this takes too long to start up and takes a lot of memory as the larger host application has over 1000 dependencies registered. I figure it must be possible to create a host with a DI container referring to the same one as its parent. Any ideas as to how this could be done?
Edit: I should clarify that I can not modify the larger host application in any way as my application is a plugin.