【问题标题】:Handling plugins with configuration with Ninject使用 Ninject 处理带有配置的插件
【发布时间】:2013-12-17 17:18:56
【问题描述】:

我正在编写一个应用程序,其中各种业务逻辑位可以位于单独的程序集中,然后这些位用于构建一个需要两个接口的对象,如下所示:

public interface ISubjectSource {}
public interface IStudySource {}

public class Worker
{
   public Worker(ISubjectSource subjectSource, IStudySource studySource)
   {
     ....
   }
}

单独的程序集可以包含ISubjectSourceIStudySource 的各种实现。然后连同一个配置文件:

"Study1":{  
    "assemblies":["Compare.Sql.dll"],   
    "mappingSource":"Compare.Sql.SqlSubjectSource,Compare.Sql",
    "studySource":"Compare.Sql.SqlStudySource,Compare.Sql", 
}

其中描述了为“Study1”构建工人所需的内容。当各种来源有自己的依赖关系时,我的问题就出现了(例如,Sql Sources 采用一个接口来处理创建连接字符串可能来自不同文件的连接)。

所以,我的问题归结为:我如何告诉 Ninject 当我为 study1 创建一个 worker 时,确保它获得这些对象,但是当我为 Study2 创建一个 worker 时,它会获得另一组对象?

【问题讨论】:

    标签: ninject


    【解决方案1】:

    这是我们的工作:

    我们有一个接口IPlugin,带有一个标识符和一个可枚举的模块。

    public interface IPlugin
    {
      string Identification { get; }
    
      IEnumerable<Type> Modules { get; }
    }
    

    模块中的类型必须全部继承自NinjectModuleIdentification 是您在配置中引用的内容,例如“我想使用插件 SQLStudySource”或“我想使用插件 FileStudySource”。

    然后我们使用https://github.com/ninject/ninject.extensions.conventions 绑定来自特定程序集的所有 IPlugin 实现(如插件文件夹中的所有程序集):

    this.Bind(x => x.FromAssembliesInPath("foo")
                .SelectAllClasses()
                .InheritedFrom<IPlugin>()
                .BindTo<IPlugin>());
    

    接下来根据配置激活插件(或者更确切地说是它们的模块):

    IEnumerable<Type> activatedPluginModules = kernel
      .GetAll<IPlugin>()
      .Where(plugin => configuration.ActivatedPluginIdentifications.Contains(plugin.Identification)
      .SelectMany(x => x.Modules)
      .Distinct();
    
    foreach(Type module in activatedPluginModules) 
    {
      kernel.Load(module);
    }
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2023-03-30
      • 2013-04-28
      • 2017-12-28
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多