Is it necessary to control the amount of dbContext objects that are being created?
I thought it might be safer to apply the Singleton pattern to my customDbContext class. However, when I execute the Update-Database command in the Package Manager Console I get an error that my dbContext does not have a default constructor (due to me implementing the Singleton pattern).
Question: Is it really that much safer or should I go for the simple solution?
public class WebshopContext : DbContext
{
private static WebshopContext database;
private WebshopContext() : base("DefaultConnection") { }
public static WebshopContext GetInstance() {
if (database != null)
{
return database;
}
else {
database = new WebshopContext();
return database;
}
}
}
DbContextcorresponds to a unit of work. You should not create a singleton as that would be shared among all your request. You should not create a new DbContext for each database request since different database requests in a single unit of work (could be a method in your controller) should share the same entities to be compatible.Create one
DbContextfor each command in your controller and pass that around, when the request is complete you submit changes if it is an update request.If you don’t want to pass your DbContext around all the time you could create a “scope” for your
DbContext.