WPF .Net Core Dependency Injection & View Models
-
I'm setting up a sample .Net Core WPF app. I want to implement Unit Testing and I'd like to learn the right way to use DI with Views & View Models. So far I have this
public partial class App : Application
{
public static IHost? AppHost { get; private set; }public App() { AppHost = Host.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { services.AddSingleton<LoginViewModel>(); services.AddSingleton<LoginView>(); }) .Build(); } protected override void OnStartup(StartupEventArgs e) { AppHost!.Start(); base.OnStartup(e); } protected override async void OnExit(ExitEventArgs e) { await AppHost!.StopAsync(); base.OnExit(e); }
}
How does the LoginView get the LoginViewModel? In my .Net Framework apps I use a ViewModel locator. Is there a best practice with WPF .Net Core, or would that work fine here also? Thanks
If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.
-
I'm setting up a sample .Net Core WPF app. I want to implement Unit Testing and I'd like to learn the right way to use DI with Views & View Models. So far I have this
public partial class App : Application
{
public static IHost? AppHost { get; private set; }public App() { AppHost = Host.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { services.AddSingleton<LoginViewModel>(); services.AddSingleton<LoginView>(); }) .Build(); } protected override void OnStartup(StartupEventArgs e) { AppHost!.Start(); base.OnStartup(e); } protected override async void OnExit(ExitEventArgs e) { await AppHost!.StopAsync(); base.OnExit(e); }
}
How does the LoginView get the LoginViewModel? In my .Net Framework apps I use a ViewModel locator. Is there a best practice with WPF .Net Core, or would that work fine here also? Thanks
If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.
Watch this: Models - WPF MVVM TUTORIAL #1 - YouTube[^] - he will answer many questions for you, including this one!
Graeme
"I fear not the man who has practiced ten thousand kicks one time, but I fear the man that has practiced one kick ten thousand times!" - Bruce Lee