@@ -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 ) ;
@@ -602,16 +608,18 @@ private static void TrySetDefaultScopedLifestyle(Container container)
602608 private static void HookAspNetCoreHostHostedServiceServiceProviderInitialization (
603609 SimpleInjectorAddOptions options )
604610 {
605- // ASP.NET Core 3's new Host class resolves hosted services much earlier in the pipeline. This
606- // registration ensures that the IServiceProvider is assigned before such resolve takes place,
607- // to ensure that that hosted service can be injected with cross-wired dependencies.
608- options . Services . AddSingleton < IHostedService > ( provider =>
611+ // ASP.NET Core 3's new Host class resolves hosted services much earlier in the pipeline. This registration
612+ // ensures that the IServiceProvider is assigned before such resolve takes place, to ensure that that
613+ // hosted service can be injected with cross-wired dependencies.
614+ // We must ensure that this hosted service gets resolved by ASP.NET before any other hosted service is
615+ // resolve; that's why we do the Insert(0).
616+ options . Services . Insert ( 0 , ServiceDescriptor . Singleton < IHostedService > ( provider =>
609617 {
610618 options . SetServiceProviderIfNull ( provider ) ;
611619
612620 // We can't return null here, so we return an empty implementation.
613621 return new NullSimpleInjectorHostedService ( ) ;
614- } ) ;
622+ } ) ) ;
615623 }
616624
617625 private static void EnsureMethodOnlyCalledOnce (
0 commit comments