如何将DIY

时间:2018-11-24 18:54:38

标签: c# wpf dependency-injection

我设法使用Unity设置了DI:

App.xaml.cs

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

    IUnityContainer container = new UnityContainer();

    container.RegisterType<ApplicationDbContext>();

    container.RegisterType<MainWindowViewModel>();
    container.RegisterType<PageConsignmentsViewModel>();

    container.RegisterType<MainWindow>();
    container.RegisterType<PageConsignments>();

    var mainWindow = container.Resolve<MainWindow>();
    var pc = container.Resolve<PageConsignments>();
    mainWindow.Show();
}

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    [Dependency]
    public MainWindowViewModel ViewModel
    {
        set => DataContext = value;
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

MainWindowViewModel.cs

public class MainWindowViewModel : BaseViewModel
{
    private Page currentPage;
    public Page CurrentPage { get { return currentPage; } set { currentPage = value; OnPropertyChanged("CurrentPage"); } }

    private readonly ApplicationDbContext db;

    public MainWindowViewModel(ApplicationDbContext db)
    {
        this.db = db;

        CurrentPage = new PageConsignments();
    }

    #region Navigation Menu Commands
    ...
    #endregion
}

我可以看到Db已被注入MainWindow中并且DataContext是正确的(MainWindowViewModel的新实例)。

但是,当我使用ConsignmentsPage导航到CurrentPage = new PageConsignments时,我看到ConsingmentsPage.DataContext为空-大概是因为这个新视图不在我的Unity容器中。

我认为我可以通过导航来解决此问题:

    IUnityContainer container = new UnityContainer();
    container.RegisterType<ApplicationDbContext>();
    container.RegisterType<PageConsignmentsViewModel>();
    var pc = container.Resolve<PageConsignments>();
    CurrentPage = pc;

而是,我想知道-是推荐的方法,还是有某种方法可以在App.OnStartup中定义所有这些DI,而不是为每次导航创建新的容器?

0 个答案:

没有答案