为什么我的瞬态DbContext缓存数据而我的作用域不缓存数据?

时间:2019-07-22 14:30:38

标签: asp.net asp.net-core dependency-injection dbcontext ef-core-2.2

我有一个DbContext配置如下:

/// <summary>
/// The extension to regsiter all DB contextes.
/// </summary>
/// <param name="services">Services.</param>
/// <param name="config">Configurations.</param>
public static void RegisterDIWithDbContext(this IServiceCollection services, IConfiguration config)
{
    services.AddDbContext<IntranetContext>(options => options.UseSqlServer(ConfigurationHelper.GetIntranetConString(config)), ServiceLifetime.Scoped);
    services.AddDbContext<RELionContext>(options => options.UseSqlServer(ConfigurationHelper.GetRelionConString(config)), ServiceLifetime.Scoped);
    services.AddDbContext<EloContext>(options => options.UseSqlServer(ConfigurationHelper.GetEloConString(config)), ServiceLifetime.Scoped);
}

因此,目前它们是作用域的(也是默认值)。 我试图将其转换为瞬态,因为我认为DbContext基本上是轻量级的,因此我可以做到(当然,我知道我会放弃几个事务功能)。

瞬态DbContext发生了一些奇怪的事情,因为几乎每个List(例如,来自实体的一个简单列表)都被缓存了,将不再接收实际的更改数据:

public async Task<List<UserCarActivity>> Execute(int userId, int month, int year)
{
    DateTime from = new DateTime(year, month, 1);
    DateTime to = from.AddMonths(1);

    var data = await this.Context.UserCarActivities
        .Include(x => x.CarActivity)
        .Where(x => x.UserId == userId && x.Date >= from && x.Date < to)
        .Include("CarActivity.RefCarCategory")
        .ToListAsync();
    return data;
}

一旦我将其切换回范围或使用AsNoTracking(),数据将是真实且“实时”的,不会被缓存。

为什么?

0 个答案:

没有答案