// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; namespace MyDriving.Utils { /// /// Simple ServiceLocator implementation. /// public sealed class ServiceLocator { static readonly Lazy instance = new Lazy(() => new ServiceLocator()); readonly Dictionary> registeredServices = new Dictionary>(); /// /// Singleton instance for default service locator /// public static ServiceLocator Instance => instance.Value; /// /// Add a new contract + service implementation /// /// Contract type /// Service type public void Add() where TService : new() { registeredServices[typeof (TContract)] = new Lazy(() => Activator.CreateInstance(typeof (TService))); } /// /// This resolves a service type and returns the implementation. Note that this /// assumes the key used to register the object is of the appropriate type or /// this method will throw an InvalidCastException! /// /// Type to resolve /// Implementation public T Resolve() where T : class { Lazy service; if (registeredServices.TryGetValue(typeof (T), out service)) { return (T) service.Value; } return null; } } }