I have simple app with MainWindow and UserControl inside.
private readonly IDateTimeService _service;
public MainWindow(IDateTimeService service)
{
_service = service;
InitializeComponent();
DataContext = this;
}
private readonly IRandomService _service;
public UserControl1(IRandomService service)
{
_service = service;
InitializeComponent();
DataContext = this;
}
This is App.xaml.cs
private readonly IHost _host;
public App()
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
ConfigureServices(services);
}).Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MainWindow>();
services.AddSingleton<UserControl1>();
services.AddTransient<IDateTimeService, DateTimeService>();
services.AddTransient<IRandomService, RandomService>();
}
protected override async void OnStartup(StartupEventArgs e)
{
await _host.StartAsync();
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
using (_host)
{
await _host.StopAsync();
}
base.OnExit(e);
}
And when I try to launch it I get null reference exception on InitializeComponent() in MainWindow.
I believe its because MainWindow tries to launch but fails, because UserControl is not ready. And UserControl tries to launch and fails because MainWindow is not initialized.
Is there a way to fix it, or Dependency Injection has certain limitations?
What I have tried:
Tried to rearrange code inside ConfigureServices without success.