| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | namespace WixToolsetTest.Converters.Mocks |
| 4 | { |
| 5 | using System; |
| 6 | using System.Collections.Generic; |
| 7 | using WixToolset.Extensibility.Services; |
| 8 | |
| 9 | public class MockCoreServiceProvider : IWixToolsetCoreServiceProvider |
| 10 | { |
| 11 | public Dictionary<Type, Func<IWixToolsetCoreServiceProvider, Dictionary<Type, object>, object>> CreationFunctions { get; } = new Dictionary<Type, Func<IWixToolsetCoreServiceProvider, Dictionary<Type, object>, object>>(); |
| 12 | |
| 13 | public Dictionary<Type, object> Singletons { get; } = new Dictionary<Type, object>() |
| 14 | { |
| 15 | { typeof(IMessaging), new MockMessaging() } |
| 16 | }; |
| 17 | |
| 18 | public void AddService(Type serviceType, Func<IWixToolsetCoreServiceProvider, Dictionary<Type, object>, object> creationFunction) => this.CreationFunctions.Add(serviceType, creationFunction); |
| 19 | |
| 20 | public void AddService<T>(Func<IWixToolsetCoreServiceProvider, Dictionary<Type, object>, T> creationFunction) where T : class => this.AddService(typeof(T), creationFunction); |
| 21 | |
| 22 | public T GetService<T>() where T : class => this.TryGetService(typeof(T), out var obj) ? (T)obj : null; |
| 23 | |
| 24 | public object GetService(Type serviceType) => this.TryGetService(serviceType, out var service) ? service : null; |
| 25 | |
| 26 | public bool TryGetService(Type serviceType, out object service) |
| 27 | { |
| 28 | if (!this.Singletons.TryGetValue(serviceType, out service)) |
| 29 | { |
| 30 | if (this.CreationFunctions.TryGetValue(serviceType, out var creationFunction)) |
| 31 | { |
| 32 | service = creationFunction(this, this.Singletons); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | return service != null; |
| 37 | } |
| 38 | |
| 39 | public bool TryGetService<T>(out T service) where T : class |
| 40 | { |
| 41 | service = null; |
| 42 | |
| 43 | if (this.TryGetService(typeof(T), out var obj)) |
| 44 | { |
| 45 | service = (T)obj; |
| 46 | } |
| 47 | |
| 48 | return service != null; |
| 49 | } |
| 50 | } |
| 51 | } |