0

I am new to Autofac. In my program.cs file I have my registrations:

var builder = new ContainerBuilder();
builder.RegisterLogger();
builder.RegisterType<GetUserFactory>().As<IGetUser>();
builder.RegisterType<MyContext>().InstancePerLifetimeScope();
builder.RegisterType<LoginForm>();
builder.RegisterType<RegisterForm>();
builder.RegisterType<MainFormView>().As<IMainFormView>().InstancePerLifetimeScope();
builder.RegisterType<MainFormPresenter>();
builder.RegisterType<TestForm>();
builder.RegisterType<PeopleReport>();
Container = builder.Build();

When I open my MainFormView it works fine the first time. But any attempt to open it a second time or any subsequent attempt states my MyContext is disposed.

using (var mainFormView = Program.Container.Resolve<IMainFormView>())
{
    mainFormView.SetTag(Program.Container.Resolve<MainFormPresenter>());

    var form = (MainFormView)mainFormView;

    form.ShowDialog();
}

My question is how should I configure Autofac so my MyContext is new-ed up for each MainFormView request?

UPDATE:

After looking more closely at my error message I see it is my MainFormView that is being disposed that is the reason for the error message not the MyContext.

Randy
  • 1,137
  • 16
  • 49
  • 2
    Use per-dependency scope: _a unique instance will be returned from each request for a service._ `builder.RegisterType().InstancePerDependency();` This is a default option, so you can simply skip last method: `builder.RegisterType()` – Fabio Aug 23 '20 at 04:06
  • @Fabio I set my `builder.RegisterType()` to a per-dependency scope. I still have the same error that my context has been disposed. – Randy Aug 24 '20 at 13:48

1 Answers1

1

I see you've got:

builder.RegisterType<MyContext>()
  .InstancePerLifetimeScope();
       ^^^^^^^^^^^^^

Database contexts should generally not be declared to have a lifetime scope. See also and also

Caius Jard
  • 72,509
  • 5
  • 49
  • 80