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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM