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?
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
SingleInstanceoften 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