Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using Ninject;
  4. using Ninject.Extensions.Conventions;
  5.  
  6. /// <summary>
  7. /// Extensions method to handle plugins
  8. /// </summary>
  9. public static class NinjectPlugin
  10. {
  11. /// <summary>
  12. /// Bind a DLL to a specified interface
  13. /// </summary>
  14. /// <typeparam name="T">T the service interface to bind to</typeparam>
  15. /// <param name="kernel"></param>
  16. /// <param name="directorypath">the path to the folder conaining the assemblies</param>
  17. public static void LoadDll<T>(this IKernel kernel, string directorypath)
  18. {
  19. if(!typeof(T).IsInterface)
  20. throw new InvalidCastException(typeof(T).Name + " Must be an interface");
  21. kernel.Bind(s => s.FromAssembliesInPath(directorypath)
  22. .Select(t => t.GetInterfaces().Any(i => i == typeof(T)))
  23. .BindSingleInterface());
  24. if (!kernel.CanResolve<T>())
  25. throw new InvalidOperationException("No assembly inside " + directorypath + " contains an implementation for interface " + typeof (T).Name);
  26. }
  27.  
  28. /// <summary>
  29. /// Bind a DLL to a specified interface. If the bining fails, bind to a fallback implementation
  30. /// </summary>
  31. /// <typeparam name="T">T the service interface to bind to</typeparam>
  32. /// <typeparam name="TFallback">The fallback implementation of the service</typeparam>
  33. /// <param name="kernel"></param>
  34. /// <param name="directorypath">the path to the folder conaining the assemblies</param>
  35. public static void LoadDll<T, TFallback>(this IKernel kernel, string directorypath)
  36. where TFallback : T
  37. {
  38. try
  39. {
  40. kernel.LoadDll<T>(directorypath);
  41. }
  42. catch (Exception e)
  43. {
  44. if (e is InvalidCastException)
  45. throw;
  46. //bind the fallback
  47. kernel.Bind<T>().To<TFallback>();
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement