Using Ninject in a plugin like architecture

前端 未结 9 2167
半阙折子戏
半阙折子戏 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: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();
            scanner.BindWith>();
        });
    
        return kernel;
    }
    
    private class PluginBindingGenerator : IBindingGenerator
    {
        private readonly Type pluginInterfaceType = typeof (TPluginInterface);
    
        public void Process(Type type, Func 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().

    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.

提交回复
热议问题