簡體   English   中英

MEF進出口無效

[英]MEF import and export not working

我試圖在不使用棱鏡的情況下創建WPF應用程序。當我試圖通過強制構造函數來通過mef在視圖中獲取視圖模型時,我的代碼中也有一個屬性注入,該注入也提供了空引用。 這是因為沒有覆蓋復合容器,如果這樣,在沒有棱鏡的應用中如何/在何處給出復合容器。 我的代碼是這樣的在xaml文件設計實例中,設置為viewmodel,而cs文件是

MainWindow.xaml.cs

public MainWindow()
    {
        InitializeComponent();            
    }

    [ImportingConstructor]
    public MainWindow(MainWindowViewModel viewModel) :this()
    {
        this.DataContext = viewModel;
        this.ViewModel = viewModel;
    }
    public MainWindowViewModel ViewModel { get; set; }

[Export] 
public class MainWindowViewModel 
{    
}

MainWindow.xaml.cs的構造函數的斷點根本沒有命中。在viewmodel內部,屬性注入也沒有命中。 我該如何解決這個問題?

這是使用PRISM 5的示例,但在PRISM 6.2.0中將以相同的方式工作。

您需要從app.xaml中刪除啟動uri。 然后確保已安裝PRISM.MEF NuGet軟件包。 像下面這樣寫一個引導程序。 (請注意,bootstrapper基類具有一系列方法,可以在所有此設置中使用適當的位置進行覆蓋。為簡單起見,我將所有方法都卡在一個方法中。)

public class MyBootstrapper : MefBootstrapper
{
    protected override DependencyObject CreateShell()
    {            
        var catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly));
        var container = new CompositionContainer(catalog);
        var shell = container.GetExport<MainWindow>().Value;
        shell.Show();
        return shell;
    }
}

在您的MainWindow中添加一個Export屬性。 這對於引導程序中的這一行將是必需的:

var shell = container.GetExport<MainWindow>().Value;

[Export]
public partial class MainWindow : Window{}

現在剩下的就是運行引導程序了:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        var bootstrapper = new MyBootstrapper();
        bootstrapper.Run();
    }
}

更新

通過執行下面描述的示例,可以很好地掌握MEF:

https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx

更新

這是實現引導程序的一種更干凈的方法。

    public class MyBootstrapper : MefBootstrapper
    {
        protected override AggregateCatalog CreateAggregateCatalog()
        {
            return new AggregateCatalog();
        }

        protected override void ConfigureAggregateCatalog()
        {
            AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(MyBootstrapper).Assembly));
        }      

        protected override CompositionContainer CreateContainer()
        {
            return new CompositionContainer(AggregateCatalog);
        }

        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
        }

        protected override DependencyObject CreateShell()
        {
            var shell = Container.GetExport<MainWindow>().Value;
            shell.Show();
            return shell;
        } 
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM