I was reading the docs of msdn. I was wondering why and what's the difference between registering for example an IHostedService in the ConfigureSerivices
or in the startup ConfigureServices
method.
I was searching for the difference but I just can't seem to find it. Does anyone know this?
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices(services =>
{
services.AddHostedService<VideosWatcher>();
});
Startup.cs
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<VideosWatcher>();
}
In the second example the hosted service is run before the web host. If it needs something that is not yet available in the container, you'll have errors. Nonetheless, this is the common approach for most cases.
In the first example the hosted service is run after the web host starts (after kestrel starts), so everything will be available.
The docs explain it here.