2016-10-12 37 views
0

我正在计划使用MEF为我的导入插件实现插件体系结构。这些插件会将各种数据导入数据库(例如客户,地址,产品等)。在WebApi应用程序中使用MEF和DI

进口插件类看起来是这样的:

public interface IImportPlugin 
{ 
    string Name { get; } 
    void Import(); 
} 

[Export(typeof(IImportPlugin))] 
public class ImportCustomers : IImportPlugin 
{ 
    private readonly ICustomerService customerService; 

    public string Name 
    { 
     get { this.GetType().Name; } 
    } 

    public ImportCustomers(ICustomerService _customerService) 
    { 
     customerService = _customerService; 
    } 

    public void Import() {} 
} 

然后我有一个控制器,它首先获取所有输入插件如下:

public IHttpActionResult GetImportPlugins() 
{ 
    var catalog = new AggregateCatalog(); 

    catalog.Catalogs.Add(new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin"))); 

    var directoryCatalog = new DirectoryCatalog(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins")); 
    catalog.Catalogs.Add(directoryCatalog); 

    var container = new CompositionContainer(catalog); 
    container.ComposeParts(); 

    var list = container.GetExportedValues<IImportPlugin>().Select(x => x.Name); 
    return Ok(list); 
} 

进口插件需要引用我的Services总成因为这是BL发生的地方。注册我的服务与Autofac主要的WebAPI项目如下:

builder.RegisterAssemblyTypes(assemblies) 
    .Where(t => t.Name.EndsWith("Service")) 
    .AsImplementedInterfaces() 
    .InstancePerRequest(); 

是否有可能通过不同的服务,不同的输入插件?

例如,如果我进口的产品我需要通过ProductService,如果我输入我的客户可能需要通过CustomerServiceAddressService

如何在插件中注入这些服务(通过构造函数就像在控制器中一样)?

+0

难道你不能在你的插件注册模块?例如,在ninject中,您可以指定注册插件依赖关系的NinjectModule。然后,在主要模块中,您只需将所有模块注册到插件文件夹中,并且所有BL接口实现都将在插件中提供。 – eocron

回答

0

对于插件式的建筑风格,你需要三样东西:

  • 合同(basicaly组件只包含接口和简单 对象withouth的BL)。这将用作插件的API。另外,在这里你可以指定IImportPlugin接口。

  • 负责任的模块将从某个文件夹或其他地方加载插件模块。

  • 模块在您创建的每个插件中,将您的插件注册为II容器内的IImportPlugin。

您可以循环像这样注册您的插件模块:

builder.RegisterAssemblyModules(/*plugin 'Assembly' goes here*/); 

在你的插件组装,在具体的模块,您只需指定你的插件注册:

public class MyPluginModule : Module 
{ 
    protected override void Load(ContainerBuilder builder) 
    { 
     builder.Register<ImportCustomers>().As<IImportPlugin>(); 
    } 
} 

然后在插件实施ImportCustomer您可以使用从合同汇编(例如e您的ICustomerService接口)。如果你的系统为你的插件注册了依赖关系 - 它将会成功加载到DI容器中。

+0

我不想注册使用DI的插件,因为它们必须事先知道,它使用MEF破坏了插件体系结构的目的。 –

相关问题