我想在 ClassLibrary 中使用 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”的“Plugins”属性。
有人有解决方案吗?