2015-12-22 166 views
0

可有人請告訴我建設中的app.xaml.cs文件中的MEF組合容器,而無需使用棱鏡或控制檯應用程序,這是沒有問題的一個例子。MEF和WPF無棱鏡

出口工作,但進口才能看到只用棱鏡,我不希望使用工作不和所有的例子。進口將工作,如果在App.xaml.cs文件,但我不明白爲什麼導入不會在MainWindow.cs工作,一切都在根組件。

我可以得到它,如果我做組成的主窗口構造函數,但我想如果可能的話在app.xaml.cs組成組成。

下面是一個示例(我實際使用MVVM但這個例子的行爲與代碼相同的後面)。

public partial class App : Application 
{ 
    public App() 
    { 
     ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose; 

    } 

    protected override void OnStartup(StartupEventArgs e) 
    { 
     base.OnStartup(e); 



     Compose(); 

     var window = new MainWindow(); 
     window.Show(); 

    } 

    public void Compose() 
    { 
     var catalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog(".")); 
     var container = new CompositionContainer(catalog); 
     container.ComposeParts(this); 
    } 


} 

[Export] 
public class MessagePlugin 
{ 
    public string GetMessage() 
    { 
     return "Successfully composed message"; 
    } 

} 

public partial class MainWindow : Window 
{ 
    [Import] 
    public MessagePlugin plugin { get; set; } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     Loaded += MainWindow_Loaded; 

    } 


    private void MainWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     var p = plugin; <-------------------------------NULL 
     MessageBox.Show(p.GetMessage()); 

    } 
} 
+0

您需要創建一個[mcve]來說明您正在嘗試執行的操作。從那裏,人們可以告訴你你錯了什麼。 – Will

+0

在這裏你去,例如增加 – Fab

+1

您還沒有叫'撰寫()'任何地方App.xaml.cs.或者是錯字? – vendettamit

回答

0
public partial class App : Application 
{ 
    private CompositionContainer container; 

    [Import(typeof(Window))] 
    public Window TheMainWindow { get; set; } 


    public App() 
    { 
     ShutdownMode = ShutdownMode = ShutdownMode.OnMainWindowClose; 
    } 


    protected override void OnStartup(StartupEventArgs e) 
    { 
     base.OnStartup(e); 

     TheMainWindow = new MainWindow(); 

     Compose(); 

     Application.Current.MainWindow = TheMainWindow; 
     Application.Current.MainWindow.Show(); 

    } 

    public void Compose() 
    { 
     var catalog = new AggregateCatalog(); 
     catalog.Catalogs.Add(new AssemblyCatalog(typeof(App).Assembly)); 
     container = new CompositionContainer(catalog); 
     container.ComposeParts(this); 
    } 

} 

[導出(typeof運算(窗口))] 公共部分類主窗口:窗口 { [導入] 公共MessagePlugin插件{得到;組; }

public MainWindow() 
    { 
     InitializeComponent(); 
     Loaded += MainWindow_Loaded; 

    } 


    private void MainWindow_Loaded(object sender, RoutedEventArgs e) 
    { 
     var p = plugin; 

     if (p != null) 
     { 
      MessageBox.Show(p.GetMessage()); 
     } 
     else 
     { 
      MessageBox.Show("Plugin NOT Composed"); 
     } 


    } 
} 
+0

爲什麼要添加TheMainWindow = new MainWindow();在啓動方法? – Shelvin