Which lifecycle is best for using Entity Framework with Autofac in ASP.Net MVC?

169 Views Asked by At

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?

1

There are 1 best solutions below

0
Daniel On

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