我很好奇为什么会发生以下情况:
当我在导入的程序集中使用 ImportMany 并在导入的程序集的构造函数中调用 compose 方法时,我可以看到 ImportMany IEnumerable get 已填充,但是一旦我走出构造函数并返回父程序集的代码,移动鼠标光标在刚刚导入的程序集上,它的 ImportMany IENumerable 是空的!
如果我在从“父”程序集调用的方法中进行组合,一切正常。
意味着以下内容不起作用:示例代码(父):
private CompositionContainer modules;
private AggregateCatalog catalogOfModules = new AggregateCatalog();
#region MEF Imports
[Import(typeof(IMyTypedInterface<someOtherInterface>),AllowDefault=true)]
public someOtherInterface someObject;
public void StartProgram()
{
try
{
catalogOfModules.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + System.IO.Path.DirectorySeparatorChar + "directoryWichContainsMyAssembly"));
modules = new CompositionContainer(catalogOfModules);
modules.ComposeParts(this);
someObject.listOfModules.Count; # is 0
}
catch (CompositionException)
{
}
}
示例代码(子):
[Export(typeof(IMyTypedInterface<someOtherInterface>))]
public class ExampleChild{
[ImportMany(typeof(someInterface))]
private IEnumerable<someInterface> listOfModules;
private CompositionContainer modules;
private AggregateCatalog catalogOfModules = new AggregateCatalog();
public ExampleChild()
{
catalogOfModules.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + System.IO.Path.DirectorySeparatorChar + "someDirectoryWithAssemblies"));
modules = new CompositionContainer(catalogOfModules);
modules.ComposeParts(this);
listOfModules.Count; # is 2
}
}
============================================
但这确实有效
示例代码(父):
private CompositionContainer modules;
private AggregateCatalog catalogOfModules = new AggregateCatalog();
#region MEF Imports
[Import(typeof(IMyTypedInterface<someOtherInterface>),AllowDefault=true)]
public someOtherInterface someObject;
public void StartProgram()
{
try
{
catalogOfModules.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + System.IO.Path.DirectorySeparatorChar + "directoryWichContainsMyAssembly"));
modules = new CompositionContainer(catalogOfModules);
modules.ComposeParts(this);
if (someObject != null)
{
someObject.ComposeMethod();
someObject.listOfModules.Count; # is 2
}
}
catch (CompositionException)
{
}
}
示例代码(子):
[Export(typeof(IMyTypedInterface<someOtherInterface>))]
public class ExampleChild : IMyTypedInterface<someOtherInterface>, someOtherInterface{
[ImportMany(typeof(someInterface))]
private IEnumerable<someInterface> listOfModules;
private CompositionContainer modules;
private AggregateCatalog catalogOfModules = new AggregateCatalog();
public void ComposeMethod()
{
catalogOfModules.Catalogs.Add(new DirectoryCatalog(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + System.IO.Path.DirectorySeparatorChar + "CM"));
modules = new CompositionContainer(catalogOfModules);
modules.ComposeParts(this);
listOfModules.Count; # is 2
}
}
有人可以向我解释这种行为的原因吗?