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);
}
所以我們完全不需要手動去指定(▽)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/93277.html
標籤:.NET Core
上一篇:Abp vNext 自定義 Ef Core 倉儲引發例外
下一篇:HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process
