1+ namespace AgileObjects . AgileMapper . Testing
2+ {
3+ using System ;
4+ using System . Collections . Generic ;
5+ using System . Linq ;
6+ using NetStandardPolyfills ;
7+
8+ /// <summary>
9+ /// A stub service provider implementation, providing a simple GetService(Type) method for a set of predefined objects.
10+ /// </summary>
11+ public class StubServiceProvider
12+ {
13+ private readonly Dictionary < Type , object > _services ;
14+
15+ /// <summary>
16+ /// Initializes a new instance of the <see cref="StubServiceProvider"/> class using the given <paramref name="services"/>.
17+ /// Services will be cached in a Dictionary{Type, object} against their concrete and implemented interface Types; if more
18+ /// than one supplied object is of the same Type or implements the same interface, an Exception will be thrown.
19+ /// </summary>
20+ /// <param name="services">The objects to store and later make available in the service provider.</param>
21+ public StubServiceProvider ( params object [ ] services )
22+ {
23+ _services = services
24+ . SelectMany ( s => new [ ] { s . GetType ( ) } . Concat ( s . GetType ( ) . GetAllInterfaces ( ) ) . Select ( t => new
25+ {
26+ Service = s ,
27+ Type = t
28+ } ) )
29+ . ToDictionary ( d => d . Type , d => d . Service ) ;
30+ }
31+
32+ /// <summary>
33+ /// Gets the stored object of the given <paramref name="serviceType"/>, or attempts to create
34+ /// one using its parameterless constructor, if none was supplied in the constructor. If the
35+ /// Type was not supplied in the constructor and has no parameterless constructor, an Exception
36+ /// is thrown.
37+ /// </summary>
38+ /// <param name="serviceType">The Type of the service to retrieve.</param>
39+ /// <returns>
40+ /// The stored object of the given <paramref name="serviceType"/>, or ones created using
41+ /// its parameterless constructor, if none was supplied in the constructor.
42+ /// </returns>
43+ public object GetService ( Type serviceType )
44+ {
45+ if ( _services . TryGetValue ( serviceType , out var service ) )
46+ {
47+ return service ;
48+ }
49+
50+ return _services [ serviceType ] = Activator . CreateInstance ( serviceType ) ;
51+ }
52+ }
53+ }
0 commit comments