我设法使用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,而不是为每次导航创建新的容器?