Click here to Skip to main content
15,867,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have simple app with MainWindow and UserControl inside.

C#
private readonly IDateTimeService _service;
        public MainWindow(IDateTimeService service)
        {
            _service = service;
            InitializeComponent();
            DataContext = this;
        }

C#
private readonly IRandomService _service;
        public UserControl1(IRandomService service)
        {
            _service = service;
            InitializeComponent();
            DataContext = this;
        }

This is App.xaml.cs
C#
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.
Posted
Updated 9-May-21 3:33am
v2
Comments
The Other John Ingram 8-May-21 20:00pm    
Is this a service? because if it is you can not have a gui.
George Swan 9-May-21 3:50am    
Try setting the apps MainWindow
Application.Current.MainWindow = mainWindow;
Application.Current.MainWindow.Show();

1 solution

Don't do this in your constructor. Use OnStartup in the App class to handle it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900