@@ -73,12 +73,18 @@ public static IServiceCollection AddSimpleInjector(
7373 // Set lifestyle before calling setupAction. Code in the delegate might depend on that.
7474 TrySetDefaultScopedLifestyle ( container ) ;
7575
76- HookAspNetCoreHostHostedServiceServiceProviderInitialization ( options ) ;
77-
7876 setupAction ? . Invoke ( options ) ;
7977
8078 RegisterServiceScope ( options ) ;
8179
80+ // Unfortunately, the addition of the IHostedService breaks Azure Functions. Azure Functions do no support
81+ // IHostedService. See: https://stackoverflow.com/questions/59947132/. This is why we had to make this
82+ // conditional.
83+ if ( options . EnableHostedServiceResolution )
84+ {
85+ HookAspNetCoreHostHostedServiceServiceProviderInitialization ( options ) ;
86+ }
87+
8288 if ( options . AutoCrossWireFrameworkComponents )
8389 {
8490 AddAutoCrossWiring ( options ) ;
@@ -597,16 +603,18 @@ private static void TrySetDefaultScopedLifestyle(Container container)
597603 private static void HookAspNetCoreHostHostedServiceServiceProviderInitialization (
598604 SimpleInjectorAddOptions options )
599605 {
600- // ASP.NET Core 3's new Host class resolves hosted services much earlier in the pipeline. This
601- // registration ensures that the IServiceProvider is assigned before such resolve takes place,
602- // to ensure that that hosted service can be injected with cross-wired dependencies.
603- options . Services . AddSingleton < IHostedService > ( provider =>
606+ // ASP.NET Core 3's new Host class resolves hosted services much earlier in the pipeline. This registration
607+ // ensures that the IServiceProvider is assigned before such resolve takes place, to ensure that that
608+ // hosted service can be injected with cross-wired dependencies.
609+ // We must ensure that this hosted service gets resolved by ASP.NET before any other hosted service is
610+ // resolve; that's why we do the Insert(0).
611+ options . Services . Insert ( 0 , ServiceDescriptor . Singleton < IHostedService > ( provider =>
604612 {
605613 options . SetServiceProviderIfNull ( provider ) ;
606614
607615 // We can't return null here, so we return an empty implementation.
608616 return new NullSimpleInjectorHostedService ( ) ;
609- } ) ;
617+ } ) ) ;
610618 }
611619
612620 private static void EnsureMethodOnlyCalledOnce (
0 commit comments