Using Ninject in a plugin like architecture

前端 未结 9 2107
半阙折子戏
半阙折子戏 2020-12-07 10:05

I\'m learning DI, and made my first project recently.

In this project I\'ve implement the repository pattern. I have the interfaces and the concrete implementations.

相关标签:
9条回答
  • 2020-12-07 10:24

    This question applies to the same answer I provided over here: Can NInject load modules/assemblies on demand?

    I'm pretty sure this is what you're looking for:

    var kernel = new StandardKernel();
    kernel.Load( Assembly.Load("yourpath_to_assembly.dll");
    

    If you look at KernelBase with reflector in Ninject.dll you will see that this call will recursively load all modules in the loaded assemblies (Load method takes an IEnumerable)

    public void Load(IEnumerable<Assembly> assemblies)
    {
        foreach (Assembly assembly in assemblies)
        {
            this.Load(assembly.GetNinjectModules());
        }
    }
    

    I'm using this for scenarios where I don't want a direct assembly reference to something that will change very frequently and I can swap out the assembly to provide a different model to the application (granted I have the proper tests in place)

    0 讨论(0)
  • 2020-12-07 10:28

    Extending on @ungood good answer, which is based on v.2, with v.3 of Ninject (currently on RC3) it could be made even easier. You needn't any IPluginGenerator anymore, just write:

    var kernel = new StandardKernel();
    kernel.Bind(scanner => scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
                                       .SelectAllClasses()
                                       .InheritedFrom<IPlugin>()
                                       .BindToAllInterfaces());
    

    Please note I'm looking for plugins implementing IPlugin (put your interface here) in the same path of the application.

    0 讨论(0)
  • 2020-12-07 10:31

    While Sean Chambers' solution works in the case that you control the plugins, it does not work in the case where plugins might be developed by third parties and you don't want them to have to be dependent on writing ninject modules.

    This is pretty easy to do with the Conventions Extension for Ninject:

    public static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
    
        kernel.Scan(scanner => {
            scanner.FromAssembliesInPath(@"Path\To\Plugins");
            scanner.AutoLoadModules();
            scanner.WhereTypeInheritsFrom<IPlugin>();
            scanner.BindWith<PluginBindingGenerator<IPlugin>>();
        });
    
        return kernel;
    }
    
    private class PluginBindingGenerator<TPluginInterface> : IBindingGenerator
    {
        private readonly Type pluginInterfaceType = typeof (TPluginInterface);
    
        public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
        {
            if(!pluginInterfaceType.IsAssignableFrom(type))
                return;
            if (type.IsAbstract || type.IsInterface)
                return;
            kernel.Bind(pluginInterfaceType).To(type);
        }
    }
    

    You can then get all loaded plugins with kernel.GetAll<IPlugin>().

    The advantages of this method are:

    1. Your plugin dlls don't need to know that they are being loaded with ninject
    2. The concrete plugin instances will be resolved by ninject, so they can have constructors to inject types the plugin host knows how to construct.
    0 讨论(0)
  • 2020-12-07 10:37

    I think no need to framework. This tutorial is solved your problem http://www.codeproject.com/KB/cs/c__plugin_architecture.aspx

    0 讨论(0)
  • 2020-12-07 10:38

    I got this as a hit for Activator.CreateInstance + Ninject and just wanted to point out something in this area - hopefully it will inspire someone to come up with a real killer answer to this question on SO.

    If you havent yet gone to the trouble of auto-scanning Modules and classes and registering them with Ninject properly, and are still creating your plugin via Activator.CreateInstance, then you can post-CreateInstance inject the dependencies in via

    IKernel k = ...
    var o = Activator.CreateInstance(...);
    k.Inject( o );
    

    Of course, this would only be a temporary solution on the way to something like http://groups.google.com/group/ninject/browse_thread/thread/880ae2d14660b33c

    0 讨论(0)
  • 2020-12-07 10:38

    The problem is that you might need to recompile if the object you setup in the load of your module are used inside the program. The reason is that you program might not have the latest version of the assembly of your class. Example, if you create a new concrete class for one of your interface, let say you change the plugin dll. Now, Injector will load it, fine but when it will be returned inside your program (kernel.get(...)) your program might not have the assembly and will throw an error.

    Example of what I am talking about:

    BaseAuto auto = kernel.Get<BaseAuto>();//Get from the NInjector kernel your object. You get your concrete objet and the object "auto" will be filled up (interface inside him) with the kernel.
    
    //Somewhere else:
    
    public class BaseModule : StandardModule
    {
            public override void Load(){
                Bind<BaseAuto>().ToSelf();
                Bind<IEngine>().To<FourCylinder>();//Bind the interface
            }     
     }
    

    If you have create a new FourCylinder called SixCylinder, your real program will not have any reference to your new object. So, once you will load from the PlugIn the BaseModule.cs you might get some trouble with the reference. To be able to do it, you will need to distribute the new dll of this concrete implementation with your plugin that will have the Module that Injector will require to load the Interface to Concrete class. This can be done without problem but you start to have a whole application that reside on loading from Plugin and it might be problematic in some points. Be aware.

    BUT, if you do want some PlugIn information you can get some tutorial from CodeProject.

    0 讨论(0)
提交回复
热议问题