为什么在 EF Core 中每次 api 调用后都会自动处理 DbContext?

Why DbContext autometically disposed after every api call in EF Core?

我正在使用 [存储库和 UOW] 模式与 EF Core 一起工作。

问题

大多数情况下,在每次成功调用上下文后都会处理并抛出错误。

扩展方法

public static IServiceCollection AddDataAccessConfig<C>(this IServiceCollection services) where C : DbContext
{
    RegisterDataAccess<C>(services);
    return services;
}

private static void RegisterDataAccess<C>(IServiceCollection services) where  C : DbContext
{
    services.TryAddScoped<IUnitOfWork<C>, UnitOfWork<C>>();
}

配置服务

//Register Context           
services.AddDataAccessConfig<MyDbContext>();
services.AddDbContext<MyDbContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DbCon"));
});

//Register Repository      
services.TryAddScoped<IUserRepository, UserRepository>();   

我试过使用下面的代码。但是运气不好

TryAddTransient

services.TryAddTransient<IUserRepository, UserRepository>();

知识库基础

protected RepositoryBase(IUnitOfWork<C> unitOfWork)
{
    UnitOfWork = unitOfWork;
    _dbSet = UnitOfWork.GetContext.Set<E>(); // THIS LINE THROW ERROR
}

UOW

public UnitOfWork(C dbcontext)
{
    _dbContext = dbcontext;
}

public C GetContext
{
    get { return _dbContext; }
}

示例调用服务

public IActionResult ByUser(string uid, string pwd)
{
    var result = _userRepository.GetValidUser(uid, pwd);

    if (string.IsNullOrEmpty(result))
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(result));
    }
}

改变 IUserRepository 的生命周期不会影响 DbContext 的生命周期。 AddDbContextoverload 允许您指定 DbContext 的生命周期。例如

services.AddDbContext<MyDbContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DbCon"));
}, ServiceLifetime.Transient);

默认 ServiceLifetime.Scoped 只有在 ASP.NET 核心应用程序中才真正有效。有关详细信息,请参阅 here