簡體   English   中英

為什么在EF Core中的每個api調用之后都會自動丟棄DbContext?

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

我正在使用[Repository&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
}

OW

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 AddDbContext重載使您可以指定DbContext的生存期。 例如

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

僅當您在ASP.NET Core應用程序內部時,默認的ServiceLifetime.Scoped才能真正正常工作。 有關更多信息,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM