volosoft / castle-windsor-ms-adapter

Castle Windsor ASP.NET Core / Microsoft.Extensions.DependencyInjection Adapter
https://www.nuget.org/packages/Castle.Windsor.MsDependencyInjection
MIT License
85 stars 29 forks source link

This package causes a hang when using a hostbuilder in a WPF app #41

Open tstedel opened 3 years ago

tstedel commented 3 years ago

The following code will cause this host to hang forever (if you try to stop your app by closing the main window)

    public App()
    {
        Startup += App_Startup;
        Exit += App_Exit;
    }

    private async void App_Exit(object sender, ExitEventArgs e)
    {
        try
        {
            await this.host.StopAsync(TimeSpan.FromSeconds(5));
        }
        catch (Exception ex)
        {
            if (this.logger == null)
                Trace.TraceError("Error when stopping app: {0}", ex);
            else
                this.logger.LogError(ex, "Error when stopping app");
        }
        finally
        {
            this.host.Dispose();
            this.host = null;
        }
    }

    private async void App_Startup(object sender, StartupEventArgs e)
    {
        host = CreateHostBuilder().Build();

        this.logger = host.Services.GetService<ILogger<App>>();

        try
        {
            await this.host.StartAsync();

            var mainWindow = host.Services.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }
        catch (Exception ex)
        {
            if (this.logger == null)
                Trace.TraceError("Error when starting app: {0}", ex);
            else
                this.logger.LogError(ex, "Error when starting app");

            Current.Shutdown(-1);
        }
    }

    public IHostBuilder CreateHostBuilder()
    {
        var hostBuilder = new HostBuilder()
            .UseServiceProviderFactory(new WindsorServiceProviderFactory());

        return hostBuilder;
    }
maliming commented 3 years ago

hi

Can you confirm this is related to WindsorServiceProviderFactory?

tstedel commented 3 years ago

WpfApp2.zip

If you run this application, and then close the main window, the application will never shut down.

If I use the official package located at https://www.nuget.org/packages/Castle.Windsor.Extensions.DependencyInjection/ the problem goes away. In this case, you can change the using statements.

maliming commented 3 years ago

Now that there is the Castle.Windsor.Extensions.DependencyInjection package, maybe you can use it directly.