1. 程式人生 > >關於EFCore執行緒內唯一

關於EFCore執行緒內唯一

EntityFramework的執行緒內唯一

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;  
            }   

EntityFrameworkCore的執行緒內唯一

我們都知道.net Core的資料庫上下文物件是在容器裡註冊,在用到的時候通過依賴注入建立的,那要如何保證每次請求只建立一個物件呢?
我們可以在註冊的時候,通過設定ServiceLifetime屬性來達到目的。

            services.AddDbContext<MyContext>(options =>
            {
                // var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
                var connectionString = Configuration.GetConnectionString("DefaultConnection");
                options.UseSqlite(connectionString);
            },ServiceLifetime.Scoped);

通過檢視AddDbContext這個方法我們可以發現,ServiceLifetime這個屬性預設就是每次請求建立一次

        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);
        }

所以我們完全不需要手動去指定(^▽^