Home > OS >  Getting issue with the dependency injection asp core 6 with winforms creation?
Getting issue with the dependency injection asp core 6 with winforms creation?

Time:03-05

System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'Form2'.'

CodePudding user response:

The form is disposed when closed.

I would suggest using a factory

static void Main() {
    ApplicationConfiguration.Initialize();

    var builder = new HostBuilder()
        .ConfigureServices((hostContext, services) => {
            services.AddTransient<Form1>();
            services.AddTransient<Form2>();
            //Form2 factory delegate
            services.AddSingleton<Func<Form2>>(sp => () => sp.GetRequiredService<Form2>());
        });

    var host = builder.Build();

    using (var serviceScope = host.Services.CreateScope()) {
        IServiceProvider services = serviceScope.ServiceProvider;
        Application.Run(services.GetRequiredService<Form1>());
    }
}

to initialize a new form every time the button is clicked.

public partial class Form1 : Form {
    private readonly Func<Form2> factory;

    public Form1(Func<Form2> factory) {
        InitializeComponent();
        this.factory = factory;
    }

    private void form2ToolStripMenuItem_Click(object sender, EventArgs e) {
        Form2 form2 = factory();
        form2.MdiParent = this;
        form2.Show();
    }
}
  • Related