将MEF与抽象基类一起使用 [英] Using MEF with abstract base class
问题描述
我正在构建数据库导入应用程序,而不是我希望它具有可扩展性(可以根据需要添加自定义数据库模型).我的基本组件具有扩展类型必须实现的方法:MapData&保存数据.
I'm building a database import app than I want to be extensible (custom db models can be added as needed). My base component has methods that extended types have to implement: MapData & SaveData.
我将基类定义为抽象类,并且当扩展类型位于相同的名称空间中时,所有方法都可以正常工作.但是,我想在运行时使用MEF在其他名称空间中导入扩展类型,但是我不知道该怎么做.
I defined the base as an abstract class, and everything works when the extended types are in the same namespace. However, I want to use MEF to import extended types in a different namespace at runtime, but I can't figure out how to do that.
基类:
namespace Program
{
public abstract class Component
{
public abstract string TypeName { get; }
public abstract DataSet MapData( DataSet db );
public abstract bool SaveData();
}
}
扩展类(在单独的项目中):
Extended class (in a separate project):
using Program.Component;
namespace ExtendedType
{
[Export( typeof( Component )]
class Type1 : Component
{
public override string TypeName { get { return "Type1" } }
public override DataSet MapData( DataSet db )
{
// create various object models from db here
return db;
}
public override bool SaveData()
{
// save object models
return true;
}
}
}
程序用于导入所有扩展类型:
Program to import all extended types:
namespace Program
{
[ImportMany( typeof( Component ) )]
public IEnumerable<Component> componentTypes;
public Program()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add( new AssemblyCatalog( typeof( Component ).Assembly ) );
container = new CompositionContainer( catalog );
this.container.ComposeParts( this );
}
}
根据我所读的内容,IEnumerable上的[ImportMany]属性应在运行时填充该属性,但它始终为空. CompositionContainer也始终为空.
According to what I've read, the [ImportMany] attribute on IEnumerable should fill that at runtime but it's always empty. The CompositionContainer is always empty as well.
我设置不正确是什么?如何获得扩展组件类型的列表?
What did I set up incorrectly? How can I get a list of the extended Component types?
推荐答案
我最终创建了一个供MEF组件使用的扩展目录,并在App.Config中设置了一个变量,并将其他项目的Build目录设置为指向那里.感谢@JaredPar的帮助.
I ended up creating an Extensions directory for the MEF components to live in and setting a variable in App.Config as well as the Build directory of the other projects to point there. Thanks to @JaredPar for the help.
var extensionFolder = ConfigurationManager.AppSettings["ExtensionPath"];
var solutionPath = Directory.GetParent( System.IO.Directory.GetCurrentDirectory() ).Parent.FullName;
var catalog = new AggregateCatalog();
catalog.Catalogs.Add( new DirectoryCatalog( solutionPath + extensionFolder ) );
var container = new CompositionContainer( catalog );
container.ComposeParts( this );
这篇关于将MEF与抽象基类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!