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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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