Cannot access a disposed object in ASP.NET Core working with DbContext



Bump into this error and found out the reason you cannot spin up a task to run a injected DbContext which normally injected by WebAPI dependency injection of a DbContext.

Solution

Create your dbcontext manually using code below (instead of using DbContext passed in the controller)


Task.Run(() =>
{
var optionsBuilder = new DbContextOptionsBuilder<IDS_ODSContext>();
optionsBuilder.UseSqlServer("Server=(local);Database=IDS_ODS;Integrated Security=True;MultipleActiveResultSets=True;");
using (var context = new IDS_ODSContext(optionsBuilder.Options))
{
var list = context.VwValuations.ToList();
var data = list.Select(a => new ViewValuation
{
InstrumentId = a.InstrumentId.ToString(),
GrossMarketValueBase = a.Market_Value_Local_Discount,
PortfolioId = a.PortfolioId.ToString()
});
string json = JsonConvert.SerializeObject(data.ToArray());
var fileTargetPath = Path.Combine(AppConstant.fileResourceFolder, AppConstant.fileResourceName);
System.IO.File.WriteAllText(fileTargetPath, json);
}
});





Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20