EntityFramework的線程內惟一是經過httpcontext來實現的數據庫
public static DbContext DbContext() { DbContext dbContext = HttpContext.Current.Items["dbContext"] as DbContext; if (dbContext == null) { dbContext = new WebEntities(); HttpContext.Current.Items["dbContext"] = dbContext; } return dbContext; }
咱們都知道.net Core的數據庫上下文對象是在容器裏註冊,在用到的時候經過依賴注入建立的,那要如何保證每次請求只建立一個對象呢?
咱們能夠在註冊的時候,經過設置ServiceLifetime屬性來達到目的。ui
services.AddDbContext<MyContext>(options => { // var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString); },ServiceLifetime.Scoped);
經過查看AddDbContext這個方法咱們能夠發現,ServiceLifetime這個屬性默認就是每次請求建立一次this
public static IServiceCollection AddDbContext<TContext>([NotNull] this IServiceCollection serviceCollection, [CanBeNull] Action<DbContextOptionsBuilder> optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) where TContext : DbContext { return serviceCollection.AddDbContext<TContext, TContext>(optionsAction, contextLifetime, optionsLifetime); }
因此咱們徹底不須要手動去指定(^▽^).net