| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | |
|
| | 4 | | namespace PropertyGridHelpers.ServiceProviders |
| | 5 | | { |
| | 6 | |
|
| | 7 | | /// <summary> |
| | 8 | | /// A lightweight implementation of <see cref="IServiceProvider"/> that allows manual registration |
| | 9 | | /// and retrieval of service instances by type. |
| | 10 | | /// </summary> |
| | 11 | | /// <remarks> |
| | 12 | | /// This class is useful in testing scenarios or situations where full-fledged dependency injection |
| | 13 | | /// is unnecessary. It is also used internally by the <c>PropertyGridHelpers</c> library to support |
| | 14 | | /// dynamic or programmatic access to services that would otherwise be resolved via attributes. |
| | 15 | | /// </remarks> |
| | 16 | | /// <example> |
| | 17 | | /// <code> |
| | 18 | | /// var provider = new CustomServiceProvider(); |
| | 19 | | /// provider.AddService(typeof(IMyService), new MyService()); |
| | 20 | | /// var service = provider.GetService(typeof(IMyService)) as IMyService; |
| | 21 | | /// </code> |
| | 22 | | /// </example> |
| | 23 | | public class CustomServiceProvider : IServiceProvider |
| | 24 | | { |
| | 25 | | #if NET8_0_OR_GREATER |
| 72 | 26 | | private readonly Dictionary<Type, object> _services = []; |
| | 27 | | #else |
| 16 | 28 | | private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); |
| | 29 | | #endif |
| | 30 | |
|
| | 31 | | /// <summary> |
| | 32 | | /// Registers a service instance with the specified service type. |
| | 33 | | /// </summary> |
| | 34 | | /// <param name="serviceType">The type that identifies the service.</param> |
| | 35 | | /// <param name="serviceInstance">The instance of the service to associate with the type.</param> |
| | 36 | | /// <exception cref="ArgumentNullException"> |
| | 37 | | /// Thrown if <paramref name="serviceType"/> or <paramref name="serviceInstance"/> is <c>null</c>. |
| | 38 | | /// </exception> |
| 64 | 39 | | public void AddService(Type serviceType, object serviceInstance) => _services[serviceType] = serviceInstance; |
| | 40 | |
|
| | 41 | | /// <summary> |
| | 42 | | /// Retrieves a service object of the specified type. |
| | 43 | | /// </summary> |
| | 44 | | /// <param name="serviceType">An object that specifies the type of service object to retrieve.</param> |
| | 45 | | /// <returns> |
| | 46 | | /// A service object of type <paramref name="serviceType"/>, or <c>null</c> if no service of that type is regist |
| | 47 | | /// </returns> |
| | 48 | | public object GetService(Type serviceType) |
| 48 | 49 | | { |
| 56 | 50 | | _ = _services.TryGetValue(serviceType, out var service); |
| 56 | 51 | | return service; |
| 48 | 52 | | } |
| | 53 | | } |
| | 54 | | } |