Laxman
Laxman

Reputation: 47

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

Github link to sample project

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

        var builder = new HostBuilder()
         .ConfigureServices((hostContext, services) =>
         {
             services.AddTransient<Form1>();
             services.AddTransient<Form2>();

         });

        var host = builder.Build();

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

Form1 is MDI MdiParent where i am injecting Form 2

public partial class Form1 : Form
    {
        private readonly Form2 form2;

        public Form1(Form2 form2)
        {
            InitializeComponent();
            this.form2 = form2;
        }

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

When I Open Form2 by clicking from Menu it opens and close it by using [X] button When i reopen it i am getting error System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'Form2'.'

Upvotes: 0

Views: 104

Answers (1)

Nkosi
Nkosi

Reputation: 247323

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();
    }
}

Upvotes: 1

Related Questions