How do I inject dependencies into a custom WebHostService in a .Net Core project?
Before we get started, I'm reproducing my question here pretty much wholesale from my Stack Overflow question, so feel free to answer it there as well for additional internet points.
I'm trying to create a service which will run as a Windows service as described here. My problem is that the example Web Host Service constructor only takes an IWebHost parameter. My service needs a constructor more like this:
public static class HostExtensions
{
public static void RunAsMyService(this IWebHost host)
{
var webHostService = new MyService(host, loggerFactory, myClientFactory, schedulerProvider);
ServiceBase.Run(webHostService);
}
}
My Startup.cs file looks similar to this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddInMemoryCollection();
this.Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
this.container.RegisterSingleton<IConfiguration>(this.Configuration);
services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSimpleInjectorAspNetRequestScoping(this.container);
this.container.Options.DefaultScopedLifestyle = new AspNetRequestLifestyle();
this.InitializeContainer(app, loggerFactory);
this.container.Verify();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
private void InitializeContainer(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
this.container.Register(() => loggerFactory, Lifestyle.Singleton);
this.container.Register<IMyClientFactory>(() => new MyClientFactory(), Lifestyle.Transient);
this.container.Register<ISchedulerProvider>(() => new SchedulerProvider(), Lifestyle.Transient);
}
Obviously I'm using SimpleInjector as a DI container. It's registered with the IServiceCollection as detailed in the documentation.
My question is how do I access the framework's container (the IServicesCollection) in the HostExtensions class so that I can inject the necessary dependencies into MyService? For MVC controllers that's all just handled under the covers, but I don't know of any documentation detailing how to access it where needed elsewhere.
Am I trying to do something that Simple Injector doesn't support? Or is there just some obvious piece of plumbing that I'm missing?
Duplicate of https://stackoverflow.com/questions/41191543/how-do-i-inject-dependencies-into-a-custom-webhostservice-in-a-net-core-project