1+ using Autofac ;
2+ using eShopOnContainers . Core . Services . Catalog ;
3+ using System ;
4+ using System . Collections . Generic ;
5+ using System . Linq ;
6+ using System . Web ;
7+ using System . Web . Configuration ;
8+ using System . Web . UI ;
9+
10+ namespace Microsoft . eShopOnContainers . Catalog . WebForms . Modules
11+ {
12+ // Using DI with WebForms is not yet implemented.
13+ // This implementation has been adapted from this post:
14+ // https://blogs.msdn.microsoft.com/webdev/2016/10/19/modern-asp-net-web-forms-development-dependency-injection/
15+
16+ public class AutoFacHttpModule : IHttpModule
17+ {
18+ private static IContainer Container => lazyContainer . Value ;
19+
20+ private static Lazy < IContainer > lazyContainer = new Lazy < IContainer > ( ( ) => CreateContainer ( ) ) ;
21+
22+ private static IContainer CreateContainer ( )
23+ {
24+ // Configure AutoFac:
25+ // Register Containers:
26+ var settings = WebConfigurationManager . AppSettings ;
27+ var useFake = settings [ "usefake" ] ;
28+ bool fake = useFake == "true" ;
29+ var builder = new ContainerBuilder ( ) ;
30+ if ( fake )
31+ {
32+ builder . RegisterType < CatalogMockService > ( )
33+ . As < ICatalogService > ( ) ;
34+ }
35+ else
36+ {
37+ builder . RegisterType < CatalogMockService > ( )
38+ . As < ICatalogService > ( ) ;
39+ }
40+ var container = builder . Build ( ) ;
41+ return container ;
42+ }
43+
44+ public void Dispose ( )
45+ {
46+ Container . Dispose ( ) ;
47+ }
48+
49+ public void Init ( HttpApplication context )
50+ {
51+ context . PreRequestHandlerExecute += ( _ , __ ) => InjectDependencies ( ) ;
52+ }
53+
54+ private void InjectDependencies ( )
55+ {
56+ if ( HttpContext . Current . CurrentHandler is Page page )
57+ {
58+ // Get the code-behind class that we may have written
59+ var pageType = page . GetType ( ) . BaseType ;
60+
61+ // Determine if there is a constructor to inject, and grab it
62+ var ctor = ( from c in pageType . GetConstructors ( )
63+ where c . GetParameters ( ) . Length > 0
64+ select c ) . FirstOrDefault ( ) ;
65+
66+ if ( ctor != null )
67+ {
68+ // Resolve the parameters for the constructor
69+ var args = ( from parm in ctor . GetParameters ( )
70+ select Container . Resolve ( parm . ParameterType ) )
71+ . ToArray ( ) ;
72+
73+ // Execute the constructor method with the arguments resolved
74+ ctor . Invoke ( page , args ) ;
75+ }
76+
77+ // Use the Autofac method to inject any properties that can be filled by Autofac
78+ Container . InjectProperties ( page ) ;
79+
80+ }
81+ }
82+ }
83+ }
0 commit comments