1

Not the solution mentioned in the following question. Dependency Injection in .NET Core 3.0 for WPF Instead, by adding <EnableDefaultApplicationDefinition>false</EnableDefaultApplicationDefinition> to the csproj file to prevent App.xaml from automatically generating the Main method, thereby achieving a similar effect to the dependency injection of ASP.NET core.

I have seen a piece of very beautiful code that somehow get an instance of App through IServiceProvider to call Application.Run(), but I can’t remember it now, and I can’t remember the source of the original code. Can anyone help? Thank you very much.

My current code is as follows.

    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    class Program
    {
        [STAThread]
        public static void Main()
        {
            Host.CreateDefaultBuilder()
                .ConfigureServices(ConfigureServices)
                .Build()
                .Run();
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<App>();
            services.AddSingleton<MainWindow>();
        }
    }

I need to get an instance of the App class to call Application.Run().

Summpot
  • 9
  • 1
  • 3

2 Answers2

2

A working solution for me is:

    internal class Program
    {
        [STAThread]
        public static void Main()
        {
            var host = Host.CreateDefaultBuilder()
                .ConfigureServices(ConfigureServices)
                .Build();

            var app = host.Services.GetService<App>();
            if(app != null)
            {
                app.InitializeComponent();
                app.Run();
            }
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<App>();
            services.AddSingleton<MainWindow>();
        }
    }
Sza
  • 21
  • 3
0

The IServiceProvider can be found in IHost.Services.

class Program
{
    [STAThread]
    public static void Main()
    {
        var host = Host.CreateDefaultBuilder()
            .ConfigureServices(ConfigureServices)
            .Build();
        host.RunAsync();

        var app = host.Services.GetService<App>();
        app.Run();
    }

    private static void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<App>();
        services.AddSingleton<MainWindow>();
    }
}
unggyu
  • 56
  • 1
  • 1
  • 7