Net core. I am using EF core, Unit Of Work and Repository pattern. In my code I am releasing my main thread using await Task.Delay(150); Then I am trying to get DB Context but exception says Dbcontext is disposed. So Is there any way I can get DBContext again after the main thread disposes? below few are my code snippets,
services.AddDbContext<MyContext>(options =>
options.UseSqlServer(this.Configuration["AzureSQLConnectionString"]));
services.AddScoped<IUnitOfWork, UnitOfWork>();
Below is my method
public Class MyTestBusinessLogic : IMyTestBusinessLogic
{
public MyTestBusinessLogic(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
MyTestRepository= UnitOfWork.GetRepository<MyTest>();
}
private IDbRepository<MyTest> MyTestRepository{ get; set; }
public async Task MyMethod()
{
await MyTestRepository.GetFirstOrDefaultAsync(x => x.Id == Id); // works here
await Task.Delay(150);
// here after my context disposes
await MyTestRepository.GetFirstOrDefaultAsync(x => x.Id == Id); //this wont work and It will throw error inside GetFirstOrDefaultAsync method.
}
}
GetFirstOrDefaultAsync method
public class DbRepository<T> : BaseRepository<T>, IDbRepository<T> where T : class
{
private readonly DbContext dbContext;
private readonly DbSet<T> dbSet;
public DbRepository(DbContext dbContext)
{
this.dbContext = dbContext;
this.dbSet = dbContext?.Set<T>();
}
public async Task<T> GetFirstOrDefaultAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.dbSet; // throws exception saying cannot use disposed object
foreach (Expression<Func<T, object>> include in includes)
{
query = query.Include(include);
}
if (filter != null)
{
query = query.Where(filter);
}
if (orderBy != null)
{
query = orderBy(query);
}
return await query.FirstOrDefaultAsync().ConfigureAwait(false);
}
}
Can someone help me to fix this? Any help would be appreciated. Thanks