ToolBuilder.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using PixiEditor.Helpers;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. namespace PixiEditor.Models.Tools
  6. {
  7. /// <summary>
  8. /// Handles Depdency Injection of tools
  9. /// </summary>
  10. public class ToolBuilder
  11. {
  12. private readonly IServiceProvider services;
  13. private readonly List<Type> toBuild = new List<Type>();
  14. public ToolBuilder(IServiceProvider services)
  15. {
  16. this.services = services;
  17. }
  18. /// <summary>
  19. /// Constructs a new tool of type <typeparamref name="T"/> and injects all services of <paramref name="services"/>
  20. /// </summary>
  21. public static T BuildTool<T>(IServiceProvider services)
  22. where T : Tool
  23. => (T)BuildTool(typeof(T), services);
  24. /// <summary>
  25. /// Constructs a new tool of type <paramref name="type"/> and injects all services of <paramref name="services"/>
  26. /// </summary>
  27. public static Tool BuildTool(Type type, IServiceProvider services)
  28. {
  29. Tool tool = (Tool)services.Inject(type);
  30. return tool;
  31. }
  32. /// <summary>
  33. /// Adds a new tool of type <typeparamref name="T"/> to the building chain.
  34. /// </summary>
  35. public ToolBuilder Add<T>()
  36. where T : Tool
  37. => Add(typeof(T));
  38. /// <summary>
  39. /// Adds a new tool of type <paramref name="type"/> to the building chain.
  40. /// </summary>
  41. public ToolBuilder Add(Type type)
  42. {
  43. toBuild.Add(type);
  44. return this;
  45. }
  46. /// <summary>
  47. /// Builds all added tools.
  48. /// </summary>
  49. public IEnumerable<Tool> Build()
  50. {
  51. List<Tool> tools = new List<Tool>();
  52. foreach (Type type in toBuild)
  53. {
  54. tools.Add(BuildTool(type, services));
  55. }
  56. return tools;
  57. }
  58. }
  59. }