11import Foundation
22
33public class Container {
4- static var root = Container ( )
4+ @MainActor
5+ private( set) static var root = Container ( )
56
67 /// Stored object instance factories.
78 var modules : [ String : Module ] = [ : ]
@@ -29,11 +30,12 @@ public extension Container {
2930 }
3031}
3132
33+ @MainActor
3234extension Container {
3335 /// Resolves through inference and returns an instance of the given type from the current default container.
3436 ///
3537 /// If the dependency is not found, an exception will occur.
36- static func resolve< T> ( for type: AnyObject . Type ) -> T {
38+ static func resolve< T, U : InjectionKeyType > ( for type: U . Type ) -> T {
3739 guard let component: T = weakResolve ( for: type) else {
3840 fatalError ( " Dependency ' \( T . self) ' not resolved! " )
3941 }
@@ -44,19 +46,20 @@ extension Container {
4446 /// Resolves through inference and returns an instance of the given type from the current default container.
4547 ///
4648 /// If the dependency is not found, return nil
47- static func weakResolve< T> ( for type: AnyObject . Type ) -> T ? {
49+ static func weakResolve< T, U : InjectionKeyType > ( for type: U . Type ) -> T ? {
4850 root. module ( type) ? . resolve ( ) as? T
4951 }
5052
51- func module( _ type: AnyObject . Type ) -> Module ? {
53+ func module< T : InjectionKeyType > ( _ type: T . Type ) -> Module ? {
5254 let keyName = KeyName ( type) . name
5355 return modules [ keyName]
5456 }
5557}
5658
5759public extension Container {
5860 /// DSL for declaring modules within the container dependency initializer.
59- @resultBuilder enum ContainerBuilder {
61+ @resultBuilder
62+ enum ContainerBuilder {
6063 public static func buildBlock( _ modules: Module ... ) -> [ Module ] { modules }
6164 public static func buildBlock( _ module: Module ) -> Module { module }
6265 }
@@ -78,10 +81,23 @@ public extension Container {
7881 self . init ( )
7982 register ( contentsOf: [ module ( ) ] )
8083 }
84+ }
8185
86+ @MainActor
87+ public extension Container {
8288 /// Assigns the current container to the composition root.
8389 func build( ) {
8490 // Used later in property wrapper
8591 Self . root = self
8692 }
8793}
94+
95+ #if DEBUG
96+ @MainActor
97+ public extension Container {
98+ static func clear( ) {
99+ root. modules. removeAll ( )
100+ }
101+ }
102+
103+ #endif
0 commit comments