IoC.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. namespace Caliburn.Micro.Core {
  2. using System;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. /// <summary>
  6. /// Used by the framework to pull instances from an IoC container and to inject dependencies into certain existing classes.
  7. /// </summary>
  8. public static class IoC {
  9. /// <summary>
  10. /// Gets an instance by type and key.
  11. /// </summary>
  12. public static Func<Type, string, object> GetInstance = (service, key) => { throw new InvalidOperationException("IoC is not initialized."); };
  13. /// <summary>
  14. /// Gets all instances of a particular type.
  15. /// </summary>
  16. public static Func<Type, IEnumerable<object>> GetAllInstances = service => { throw new InvalidOperationException("IoC is not initialized."); };
  17. /// <summary>
  18. /// Passes an existing instance to the IoC container to enable dependencies to be injected.
  19. /// </summary>
  20. public static Action<object> BuildUp = instance => { throw new InvalidOperationException("IoC is not initialized."); };
  21. /// <summary>
  22. /// Gets an instance from the container.
  23. /// </summary>
  24. /// <typeparam name="T">The type to resolve.</typeparam>
  25. /// <param name="key">The key to look up.</param>
  26. /// <returns>The resolved instance.</returns>
  27. public static T Get<T>(string key = null) {
  28. return (T)GetInstance(typeof(T), key);
  29. }
  30. /// <summary>
  31. /// Gets all instances of a particular type.
  32. /// </summary>
  33. /// <typeparam name="T">The type to resolve.</typeparam>
  34. /// <returns>The resolved instances.</returns>
  35. public static IEnumerable<T> GetAll<T>() {
  36. return GetAllInstances(typeof(T)).Cast<T>();
  37. }
  38. }
  39. }