/src/LinFu.Reflection/PluginLoader.cs

http://github.com/philiplaureano/LinFu · C# · 62 lines · 31 code · 6 blank · 25 comment · 3 complexity · 1ceb70c5ff50ff5b12d1177341d7a83d MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. namespace LinFu.Reflection
  4. {
  5. /// <summary>
  6. /// Represents a loader class that can load
  7. /// <see cref="ILoaderPlugin{TTarget}" /> instances
  8. /// marked with a particular <typeparamref name="TAttribute" />
  9. /// type.
  10. /// </summary>
  11. /// <typeparam name="TTarget">The target type being configured.</typeparam>
  12. /// <typeparam name="TAttribute">The attribute type that marks a type as a plugin type.</typeparam>
  13. public class PluginLoader<TTarget, TAttribute> : BasePluginLoader<TTarget, TAttribute>
  14. where TAttribute : Attribute
  15. {
  16. /// <summary>
  17. /// Determines if the plugin loader can load the <paramref name="inputType" />.
  18. /// </summary>
  19. /// <remarks>The target type must implement <see cref="ILoaderPlugin{TTarget}" /> before it can be loaded.</remarks>
  20. /// <param name="inputType">The target type that might contain the target <typeparamref name="TAttribute" /> instance.</param>
  21. /// <returns><c>true</c> if the type can be loaded; otherwise, it returns <c>false</c>.</returns>
  22. public override bool CanLoad(Type inputType)
  23. {
  24. return base.CanLoad(inputType) &&
  25. typeof(ILoaderPlugin<TTarget>).IsAssignableFrom(inputType);
  26. }
  27. /// <summary>
  28. /// Loads a set of actions from a <see cref="System.Type" />
  29. /// instance.
  30. /// </summary>
  31. /// <param name="input">The target type to scan.</param>
  32. /// <returns>A set of actions which will be applied to the target <see cref="ILoader{T}" /> instance.</returns>
  33. public override IEnumerable<Action<ILoader<TTarget>>> Load(Type input)
  34. {
  35. // Create the plugin instance
  36. var plugin = Activator.CreateInstance(input) as ILoaderPlugin<TTarget>;
  37. if (plugin == null)
  38. return new Action<ILoader<TTarget>>[0];
  39. // Assign it to the target loader
  40. Action<ILoader<TTarget>> result =
  41. loader =>
  42. {
  43. // If possible, initialize the plugin
  44. // with the loader
  45. if (plugin is IInitialize<ILoader<TTarget>>)
  46. {
  47. var target = plugin as IInitialize<ILoader<TTarget>>;
  48. target.Initialize(loader);
  49. }
  50. loader.Plugins.Add(plugin);
  51. };
  52. // Package it into an array and return the result
  53. return new[] {result};
  54. }
  55. }
  56. }