[英]Why is DBContext is disposed after putting it in IMemoryCache (.NET Core / EF Core)
[英]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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.