我正在计划使用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
,如果我输入我的客户可能需要通过CustomerService
和AddressService
。
如何在插件中注入这些服务(通过构造函数就像在控制器中一样)?
难道你不能在你的插件注册模块?例如,在ninject中,您可以指定注册插件依赖关系的NinjectModule。然后,在主要模块中,您只需将所有模块注册到插件文件夹中,并且所有BL接口实现都将在插件中提供。 – eocron