Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using Ninject;
- using Ninject.Extensions.Conventions;
- /// <summary>
- /// Extensions method to handle plugins
- /// </summary>
- public static class NinjectPlugin
- {
- /// <summary>
- /// Bind a DLL to a specified interface
- /// </summary>
- /// <typeparam name="T">T the service interface to bind to</typeparam>
- /// <param name="kernel"></param>
- /// <param name="directorypath">the path to the folder conaining the assemblies</param>
- public static void LoadDll<T>(this IKernel kernel, string directorypath)
- {
- if(!typeof(T).IsInterface)
- throw new InvalidCastException(typeof(T).Name + " Must be an interface");
- kernel.Bind(s => s.FromAssembliesInPath(directorypath)
- .Select(t => t.GetInterfaces().Any(i => i == typeof(T)))
- .BindSingleInterface());
- if (!kernel.CanResolve<T>())
- throw new InvalidOperationException("No assembly inside " + directorypath + " contains an implementation for interface " + typeof (T).Name);
- }
- /// <summary>
- /// Bind a DLL to a specified interface. If the bining fails, bind to a fallback implementation
- /// </summary>
- /// <typeparam name="T">T the service interface to bind to</typeparam>
- /// <typeparam name="TFallback">The fallback implementation of the service</typeparam>
- /// <param name="kernel"></param>
- /// <param name="directorypath">the path to the folder conaining the assemblies</param>
- public static void LoadDll<T, TFallback>(this IKernel kernel, string directorypath)
- where TFallback : T
- {
- try
- {
- kernel.LoadDll<T>(directorypath);
- }
- catch (Exception e)
- {
- if (e is InvalidCastException)
- throw;
- //bind the fallback
- kernel.Bind<T>().To<TFallback>();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement