问题描述
我具有以下结构: 我有一个主机类,该类创建目录和容器,并使用[ImportMany]从目录中的dll导入类。目录和容器都包含正确的类,但是我尝试用ImportMany填充的枚举保持为空。 我将我的问题与10多个类似的案例进行了比较,但是发现的解决方案都没有帮助我。 我忽略了什么?
这里是HostClass,只需从Program.Main()实例化并调用DoStuff()。
public class HostClass
{
private CompositionContainer _container;
[ImportMany]
public IEnumerable<Lazy<IOperation,IOperationData>> operations;
public HostClass()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog(@"Path/to/Folder"));
_container = new CompositionContainer(catalog);
CompositionBatch batch = new CompositionBatch(); // Found as answer to a similar problem,but did not help in my case
batch.AddExportedValue(this._container);
try
{
this._container.Compose(batch);
this._container.ComposeParts(this);
this._container.SatisfyImportsOnce(this); // // Found as answer to a similar problem,but did not help in my case
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
public void DoStuff()
{ // Stuff with operations}
应导出的类:
[Export(typeof(IOperation))]
[ExportMetadata("Type","myType")]
class Operation: IOperation
{ // Stuff }
主机名称空间和导出的dll的名称空间都包含它们自己的接口IOperation,但是当我使用Microsoft自己的MEF教程时,这似乎不是问题。为了避免这方面的任何问题,我确实尝试在两侧都使用Import / Export(“ Teststring”),但两者均无济于事。
此外,当我在调试器中将它与调整为我的结构的MS教程逐步进行比较时,唯一的区别是,该枚举在教程中的this._container.ComposeParts(this);
之后填充,而它变为空(但不为null,至少)在我的实际应用中
谢谢!
解决方法
通过对公共接口使用单独的组件来解决此问题。
据我所知,错误似乎确实存在于我用来比较行为的示例项目中,尽管它们在宿主和导出之间没有引用,但据我所知-我只是注意到该行为无法重现,将所有类从示例手动移到我的应用程序之后。