0

I am new to Autofac and I am using it as a dependency container. I want to register my DB context. This is what I've done

public static class AutofacConfig
    {
        public static void RegisterComponents()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<MyEntities>().As<IMyEntities>().SingleInstance().PreserveExistingDefaults();
            var container = builder.Build();

            GlobalConfiguration.Configuration.UseAutofacActivator(container);
            
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

But In .net Core, I need to register my DBContext as Scoped. Is it correct to register my Entities here as SingleInstance or I should change it?

Mohammad Taherian
  • 1,622
  • 1
  • 15
  • 34

1 Answers1

0

According to MS docs here "A DbContext instance is designed to be used for a single unit-of-work." From experience I've found registering a DBContext as a SingleInstance often leads to difficult to reproduce exceptions, especially in a multi threaded environment.

I would consider giving it as smaller scope as possible to achieve a unit of work, such as InstancePerLifetimeScope

Daniel
  • 150
  • 1
  • 9