带有NavigationService的WPF依赖项注入



我正在寻找一种在WPF应用程序中使用DI的更好方法。我使用框架和NavigationService在选项卡之间进行导航。我将WPF与.NET框架4.7.2、EF Core一起使用,对于DI,我使用Microsoft.Extensions.DependencyInjection(来自.NET Core的DI(。

一切都很好,但在页面之间导航可能会有点混乱。我的主窗口是这样的,正在加载依赖项。然而,我想在UserProfile页面中使用IPersonOrchestration,并且我必须将其传入参数中才能在那里使用它。

private readonly IPersonOrchestration_personOrchestration;
public MainWindow(IPersonOrchestration personOrchestration)
{
_personOrchestration = personOrchestration;

InitializeComponent();
_mainFrame.NavigationService.Navigate(new UserProfile(personOrchestration));
}

我的UserProfile页面,我想在其中使用该编排:

private readonly IPersonOrchestration_personOrchestration;
public UserProfile(IPersonOrchestration personOrchestration)
{
_personOrchestration = personOrchestration;

InitializeComponent();
}

从UserProfile,将有更多的步骤,通过这个实现,我必须在每个步骤的每个参数中传递来自MainWindow的编排。有没有一种方法可以直接在UserProfile中初始化依赖项,而不通过导航传递参数?

好吧,我找到了一个可能的解决方案(尽管我不相信这是最好的方法(将主窗口更改为:

public readonly IPersonOrchestration _personOrchestration;
public static MainWindow AppWindow
public MainWindow(IPersonOrchestration personOrchestration)
{
AppWindow = this;
_personOrchestration = personOrchestration;

InitializeComponent();
_mainFrame.NavigationService.Navigate(new UserProfile());
}

编排是公开的,我添加了对主窗口的公开引用,因为其他页面都是";"孩子";主窗口的。然后在UserProfile中加载编排,如下所示:

private readonly IPersonOrchestration _personOrchestration;
public UserProfile()
{
if (MainWindow.AppWindow?._personOrchestration!= null)
_personOrchestration = MainWindow.AppWindow._personOrchestration;

InitializeComponent();
}

最新更新