我想在ClassLibrary中使用MEF,而不是在应用程序项目中使用MEF(ConsoleApplication和WebApplication ......)。
当我尝试这样做时(如MSDN:http://msdn.microsoft.com/en-us/library/dd460648.aspx)
class Program
{
private CompositionContainer _container;
[Import(typeof(IPlugin))]
public IPlugin Plugins;
private Program()
{
//An aggregate catalog that combines multiple catalogs
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
catalog.Catalogs.Add(new DirectoryCatalog(@".\Extensions"));
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
//Fill the imports of this object
try
{
this._container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
static void Main(string[] args)
{
Program p = new Program(); //Composition is performed in the constructor
}
}
财产:
[Import(typeof(IPlugin))]
public IPlugin Plugins;
工作正常。
编辑:
但是,我想移动进口物业& ClassLibrary中的聚合目录创建,而不是我的ConsoleApplication中的聚合目录创建。
如下所示。
在ClassLibrary [Manager.dll]中:
public class Manager
{
private CompositionContainer _container;
[Import(typeof(IPlugin))]
public IPlugin Plugins;
public Manager()
{
//An aggregate catalog that combines multiple catalogs
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
catalog.Catalogs.Add(new AssemblyCatalog(typeof(Manager).Assembly));
catalog.Catalogs.Add(new DirectoryCatalog(@".\Extensions"));
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
//Fill the imports of this object
try
{
this._container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
}
在ConsoleApplication中:
class Manager
{
static void Main(string[] args)
{
Manager m = new Manager(); //Composition is performed in the constructor
}
}
但是当我做这个改变时,我无法获得在我的ClassLibrary中始终为“null”的“插件”属性。
任何人都有解决方案吗?
答案 0 :(得分:2)
这可能只是您的目录的一个问题。如果要将属性移动到类库中,则意味着单独的程序集。目前,只有托管“程序”的程序集在您的目录中,以及“扩展程序”中的任何内容。那么,你确定你的新类库在扩展文件夹中吗?
此外,您正在编写this
,这意味着您正在编写“程序”的实例。如果您将属性移动到不同库中的其他类,则需要编写任何类的实例。
这样的事情:
class Program
{
private CompositionContainer _container;
private Program()
{
var helper = new MyOtherHelperClass();
var catalog = helper.CreateCatalog();
//Create the CompositionContainer with the parts in the catalog
_container = new CompositionContainer(catalog);
//Fill the imports of some object
try
{
var thingIWantToCompose = new OtherClassWithAnImport();
this._container.ComposeParts(thingIWantToCompose);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
static void Main(string[] args)
{
Program p = new Program(); //Composition is performed in the constructor
}
}
如果不起作用,请尝试在Visual MEFX中查看您的部件。以下是设置简短指南:Getting Started with Visual MEFX