Configuring Dbcontext as Transient

后端 未结 2 1322
借酒劲吻你
借酒劲吻你 2020-12-09 14:55

In ASP.NET Core / EntityFramework Core, the services.AddDbContext<> method will add the specified context as a scoped service. It\'s my understanding that that is the su

相关标签:
2条回答
  • 2020-12-09 15:24

    You can also create a repository class and interface which has idbcontext constructor parameter. Have all of your controller constructors use this interface in their constructor. This can be added with addtransient. This way, Microsoft still controls the dbcontext as it sees fit. Context will be managed by runtime and injected when creating repository instances when creating controllers.

    0 讨论(0)
  • 2020-12-09 15:32

    The lifetime is a parameter on AddDbContext<>(). See example:

    services.AddDbContext<ApplicationDbContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), 
             ServiceLifetime.Transient);
    

    This will add it to the service collection with transient lifetime.

    0 讨论(0)
提交回复
热议问题