博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于EFCore线程内唯一
阅读量:3963 次
发布时间:2019-05-24

本文共 1444 字,大约阅读时间需要 4 分钟。

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
(options => { // var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; var connectionString = Configuration.GetConnectionString("DefaultConnection"); options.UseSqlite(connectionString); },ServiceLifetime.Scoped);

通过查看AddDbContext这个方法我们可以发现,ServiceLifetime这个属性默认就是每次请求创建一次

public static IServiceCollection AddDbContext
([NotNull] this IServiceCollection serviceCollection, [CanBeNull] Action
optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) where TContext : DbContext { return serviceCollection.AddDbContext
(optionsAction, contextLifetime, optionsLifetime); }

所以我们完全不需要手动去指定()

转载地址:http://iakki.baihongyu.com/

你可能感兴趣的文章
游标(Cursor)
查看>>
复合语句(compound statement)
查看>>
DB2 物化查询表
查看>>
IF 语句
查看>>
循环语句
查看>>
DB2 临时表
查看>>
ITERATE、LEAVE、GOTO和RETURN
查看>>
异常处理
查看>>
存储过程
查看>>
动态SQL(Dynamic SQL)
查看>>
在存储过程之间传递数据
查看>>
迁移存储过程
查看>>
GET DIAGNOSTIC 语句
查看>>
Python 简介
查看>>
Python 注释
查看>>
Python 变量
查看>>
Python 数据类型 -- 数字
查看>>
Spring 管理对象
查看>>
Spring 自定义对象初始化及销毁
查看>>
Spring Batch 环境设置
查看>>