When should I create a new DbContext()

前端 未结 5 1676
梦毁少年i
梦毁少年i 2020-12-02 06:25

I am currently using a DbContext similar to this:

namespace Models
{
    public class ContextDB: DbContext
    {

        public DbSet

        
5条回答
  •  日久生厌
    2020-12-02 07:22

    I try to answer out of my own experience.

    1. When should I make a new DbContext / should I have one global context that I pass around?

    The Context should be injected by the dependency-injection and should not be instantiated by yourself. Best-Practice is to have it created as a scoped service by the dependency-injection. (See my answer to Question 4)

    Please also consider using a proper layered application structure like Controller > BusinessLogic > Repository. In this case it would not be the case that your controller receives the db-context but the repository instead. Getting injected / instantiating a db-context in a controller tells me that your application architecture mixes many responsibilities in one place, which - under any circumstances - I cannot recommend.

    2. Can i have one global Context that I reuse in all places?

    Yes you can have but the question should be "Should I have..." -> NO. The Context is meant to be used per request to change your repository and then its away again.

    3. Does this cause a performance hit?

    Yes it does because the DBContext is simply not made for being global. It stores all the data that has been entered or queried into it until it is destroyed. That means a global context will get larger and larger, operations on it will get slower and slower until you will get an out of memory exceptions or you die of age because it all slowed to a crawl.

    You will also get exceptions and many errors when multiple threads access the same context at once.

    4. How is everyone else doing this?

    DBContext injected through dependency-injection by a factory; scoped:

    services.AddDbContext(o => o.UseSqlServer(this.settings.DatabaseOptions.UserDBConnectionString));
    

    I hope my answers where of help.

提交回复
热议问题