@@ -19,30 +19,59 @@ public static class ConfigurationExtensions
1919 /// <returns>The IFunctionsHostBuilder.</returns>
2020 public static IFunctionsHostBuilder UseAutofacServiceProviderFactory ( this IFunctionsHostBuilder hostBuilder , Action < ContainerBuilder > configurationAction = null )
2121 {
22- var containerBuilder = new ContainerBuilder ( ) ;
23- containerBuilder . Populate ( hostBuilder . Services ) ;
24- containerBuilder . RegisterModule < LoggerModule > ( ) ;
22+ // Adding as a Singleton service will make sure post-registered
23+ // services like TelemetryClient will be in the scope.
24+ hostBuilder . Services . AddSingleton ( ( ctx ) =>
25+ {
26+ var containerBuilder = new ContainerBuilder ( ) ;
2527
26- // Call the user code to configure the container
27- configurationAction ? . Invoke ( containerBuilder ) ;
28+ containerBuilder . Populate ( hostBuilder . Services ) ;
29+ containerBuilder . RegisterModule < LoggerModule > ( ) ;
2830
29- var container = containerBuilder . Build ( ) ;
31+ // Call the user code to configure the container
32+ configurationAction ? . Invoke ( containerBuilder ) ;
3033
31- var scoped = new ScopedJobActivator ( new AutofacServiceProvider ( container ) ) ;
34+ var container = containerBuilder . Build ( ) ;
35+ return new AutofacContainer ( container ) ;
36+ } ) ;
3237
3338 // Replacing Azure Functions ServiceProvider
34- hostBuilder . Services . Replace ( ServiceDescriptor . Singleton ( typeof ( IJobActivator ) , scoped ) ) ;
35- hostBuilder . Services . Replace ( ServiceDescriptor . Singleton ( typeof ( IJobActivatorEx ) , scoped ) ) ;
39+ hostBuilder . Services . Replace ( ServiceDescriptor . Singleton ( typeof ( IJobActivator ) , typeof ( ScopedJobActivator ) ) ) ;
40+ hostBuilder . Services . Replace ( ServiceDescriptor . Singleton ( typeof ( IJobActivatorEx ) , typeof ( ScopedJobActivator ) ) ) ;
3641
3742 // This will create a scoped execution when a function is triggered.
38- hostBuilder . Services . AddScoped ( ( provider ) =>
39- {
40- var lifetimeScope = container . BeginLifetimeScope ( Scopes . RootLifetimeScopeTag ) ;
41-
42- return lifetimeScope ;
43- } ) ;
43+ hostBuilder . Services . AddScoped < ScopedContainer > ( ) ;
4444
4545 return hostBuilder ;
4646 }
4747 }
48+
49+ internal class AutofacContainer : IDisposable
50+ {
51+ public IContainer Container { get ; }
52+
53+ public AutofacContainer ( IContainer container )
54+ {
55+ Container = container ;
56+ }
57+
58+ public void Dispose ( )
59+ {
60+ Container . Dispose ( ) ;
61+ }
62+ }
63+
64+ internal class ScopedContainer : IDisposable
65+ {
66+ public ILifetimeScope Scope { get ; }
67+ public ScopedContainer ( AutofacContainer container )
68+ {
69+ Scope = container . Container . BeginLifetimeScope ( Scopes . RootLifetimeScopeTag ) ;
70+ }
71+
72+ public void Dispose ( )
73+ {
74+ Scope . Dispose ( ) ;
75+ }
76+ }
4877}
0 commit comments