在这样的架构插件使用Ninject [英] Using Ninject in a plugin like architecture

查看:177
本文介绍了在这样的架构插件使用Ninject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习DI,最近做了我的第一个项目。

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

在此项目中,我已经实现了存储库模式。我有接口和具体实现。我不知道是否有可能建立我的接口的实现为插件,dll文件,我的计划将动态加载。

In this project I've implement the repository pattern. I have the interfaces and the concrete implementations. I wonder if is possible to build the implementation of my interfaces as "plugins", dlls that my program will load dynamically.

所以,该方案可以随着时间而提高,而无需重建它,你只需将DLL的插件文件夹,更改设置,瞧!

So the program could be improved over time without having to rebuild it, you just place the dll on the "plugins" folder, change settings and voilá!

这可能吗?可以Ninject帮助呢?

Is this possible? Can Ninject help with this?

推荐答案

肖恩·钱伯斯的解决方案的情况下工作,你控制插件,它没有的情况下工作,其中的插件可能是由第三方开发,你不希望他们有依赖于书写ninject模块。

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.

这是pretty的容易做的约定延长获得Ninject:

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);
    }
}

您就可以得到所有加载的插件与 kernel.GetAll&LT; IPlugin&GT;()

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

此方法的优点是:

  1. 您的插件的dll不需要知道他们正在装载ninject
  2. 在具体的插件实例将被ninject解决,使他们能够有构造函数注入类型的插件主机知道如何构建。

这篇关于在这样的架构插件使用Ninject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆