2
我正在使用MEF的一些示例程序。在我寫的最簡單的例子,我有一個界面看起來像這樣:如何使用MEF分層零件?
public interface IDoSomething
{
void DoIt();
}
並實現它看起來像這樣一類:
[Export(typeof(IDoSomething))]
public class TestClass : IDoSomething
{
public void DoIt()
{
Console.WriteLine("TestClass::DoIt");
}
}
和裝載類插件,看起來像這樣:
public class PluginManager
{
[ImportMany(typeof(IDoSomething))]
private IEnumerable<IDoSomething> plugins;
public void Run()
{
Compose();
foreach (var plugin in plugins)
{
plugin.DoSomething();
}
}
private void Compose()
{
var catalog = new DirectoryCatalog(@".\");
var compositionContainer = new CompositionContainer(catalog);
compositionContainer.ComposeParts(this);
}
}
這似乎工作,但現在想什麼,我做的是我的具體的插件擴展本身有一個插件,是這樣的:
[Export(typeof(IDoSomething))]
public class TestClass2 : IDoSomething
{
[Import(typeof(IDoAnotherThing))]
public IDoAnotherThing Plugin { get; set; }
public void DoIt()
{
Console.WriteLine("TestClass2::DoIt");
Plugin.Func();
}
}
其中IDoAnotherThing
看起來是這樣的:
public interface IDoAnotherThing
{
void Func();
}
和我的那個具體實施看起來是這樣的:
[Export(typeof(IDoAnotherThing))]
public class AnotherPlugin: IDoAnotherThing
{
public void Func()
{
Console.WriteLine("AnotherPlugin::Func");
}
}
我看到,當我運行這個行爲,我TestClass2
實例被創建並且它的DoIt
函數被調用,但它的AnotherPlugin
實例永遠不會被調用。我看到該目錄已列出AnotherPlugin
。我在這裏做錯了什麼?
我重新創建了這個沒有任何代碼更改,它爲我工作得很好。你已經指定'TestClass2'實例被創建,但AnotherPlugin實例沒有被調用?如果它不能爲'Plugin'屬性設置導入,它會下降。還有其他事情必須發生。我們可以看到更多的代碼嗎? –