2011-11-18 38 views
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。我在這裏做錯了什麼?

+1

我重新創建了這個沒有任何代碼更改,它爲我工作得很好。你已經指定'TestClass2'實例被創建,但AnotherPlugin實例沒有被調用?如果它不能爲'Plugin'屬性設置導入,它會下降。還有其他事情必須發生。我們可以看到更多的代碼嗎? –

回答

0

想到是正確地指出了這一點,事實證明,我是,但正如馬修雅培上述評論,事實上發生了其他事情。在這種情況下,事實是我的具體類插件並不是都在同一個目錄中結束,因此我的應用程序沒有發現正確的一個。活到老,學到老。一旦我確信我擁有所有這些程序集的最新版本,一切都運行良好。