Unofficial implementation of Microsoft.Extensions.Hosting for WPF. It is inspired by Dapplo and this extensions is focused only on WPF and doesn't have Plugins, SingleInstance etc features like Dapplo. It's main feature is to provide the ability to bind DataContext with ViewModels directly in XAML where the ViewModel gets resolved by DI. This library also has few extensions packages to add features like tray icon, thread swithcing between main thread and threadpool thread, 3rd party DI support.
- HostingSimple - Minimal getting started project.
- HostingReactiveUI - More advanced example with using NLog as logging, ReactiveUI as model-view-viewmodel framework, shows how to use the TrayIcon feature.
- HostingReactiveUISimpleInjector - Same as HostingReactiveUI but it also using SimpleInjector. This library doesn't limits your to stick only with
Microsoft.DependencyInjection
. Also shows some more abstractions and internal helpers to handle another DI inside. - HostingReactiveUISimpleInjectorFlowingScope - Almost like HostingReactiveUISimpleInjector, with the difference that it shows, how can you use Flowing-Scoping(
ScopedLifestyle.Flowing
withSimpleInjector
or any other DI with similar scoping). This is even more advanced example and shows how can you support closure-scoping (The Closure Composition Model), for ambient-scoping (The Ambient Composition Model) there is usually no need for any special changes. This sample doesn't use theViewModelLocatorHost
and shows a totally different approach on how to useIViewModelLocator
and inject viewmodel for view. It also shows the usage ofMicrosoft.Extensions.Hosting.Wpf.Threading
.
This steps including the Locator feature for Views. If you don't want it then just skip to 6 and 7 step.
In fact, it has alternative method to inject ViewModels to View. Usually used when you need to use closure-scoping with DI. Please, refer to HostingReactiveUISimpleInjectorFlowingScope
sample for such scenario.
public interface IViewModelLocator
{
MainViewModel Main { get; }
ChildViewModel Child { get; }
}
public class ViewModelLocator : IViewModelLocator
{
public IServiceProvider Container { get; }
public MainViewModel Main => Container.GetRequiredService<MainViewModel>();
public ChildViewModel Child => Container.GetRequiredService<ChildViewModel>();
public ViewModelLocator(IServiceProvider container)
{
Container = container;
}
}
public class ViewModelLocatorHost : AbstractViewModelLocatorHost<IViewModelLocator>
{
}
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!--Resources that you need, for example MahApps-->
</ResourceDictionary.MergedDictionaries>
<locator:ViewModelLocatorHost x:Key="Locator"/>
</ResourceDictionary>
</Application.Resources>
5. Add in App.xaml.cs two interfaces IViewModelLocatorInitialization<ViewModelLocator>
and IApplicationInitializeComponent
public partial class App : Application, IViewModelLocatorInitialization<IViewModelLocator>, IApplicationInitializeComponent
{
public void Initialize()
{
//Here we can initialize important things. This method always runs on UI thread.
//In this example it's empty as we do not have anything to initialize like ReactiveUI
}
public void InitializeLocator(IViewModelLocator viewModelLocator)
{
//Runs after Initialize method.
//We need to set it so that our <locator:ViewModelLocatorHost x:Key="Locator"/> could resolve ViewModels for DataContext
//You can also use it as service locator pattern, but I personally recommend you to use it only inside View xaml to bind the DataContext
var viewModelLocatorHost = ViewModelLocatorHost.GetInstance(this);
viewModelLocatorHost?.SetViewModelLocator(viewModelLocator);
}
}
NB! ViewModelLocatorHost.GetInstance(this)
will automatically find the locator even if you rename it(x:Key) in App.xaml, but for better perfomance, startup time, memory usage(it will iterate through Application Dictionary) my personal recommendation is to use ViewModelLocatorHost.GetInstance(this, "Locator")
instead.
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
using IHost host = CreateHostBuilder(args)
.Build()
.UseWpfViewModelLocator<App, IViewModelLocator>(provider => new ViewModelLocator(provider));
host.Run();
}
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices(ConfigureServices);
}
private static void ConfigureServices(HostBuilderContext hostContext, IServiceCollection services)
{
services.AddLogging();
services.AddWpf<App>();
//Add our view models
services.AddTransient<MainViewModel>();
services.AddTransient<ChildViewModel>();
}
}
<StartupObject>[Namespace].Program</StartupObject>
DataContext="{Binding ViewModelLocator.Main, Mode=OneTime, Source={StaticResource Locator}}"
If you want you can use UseWpfLifetime
but it's pretty much experimental, the current solution is well adopted to use the default lifetime and was battle tested without UseWpfLifetime
.
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.UseWpfLifetime() //<-- new line
.ConfigureServices(ConfigureServices);
}