as per microsoft documentation " A DbContext instance is designed to be used for a single unit-of-work. This means that the lifetime of a DbContext instance is usually very short." what life time i choose scoped,singleton or transient? what problem occured if i use DBcontext object as singleton
CodePudding user response:
When you call
services.AddDbContext<MyContext>(options => { });
The DbContext
will be registered as a scoped service. So a new instance will be created for each and every request.
This is the most flexible approach, as it allows you to configure a different ConnectionString, based on the tenant that's associated with eg the HttpContext
(for example: a different ConnectionString depending on the HttpContext.Request.Host
)
CodePudding user response:
Reusing same instance of DbContext
will cause bugs: calling SaveChanges
will save ALL tracked objects modified by a different consumers of DbContext
.
If you worry about performance you may take a look at DbContext pooling