c# - Asp.net Core:无法访问已处置的对象(不同的错误)
问题描述
我知道这个问题经常出现,但我不得不说我花了两天时间阅读了我能找到的所有内容并且没有得到我的错误。
我创建了一个 ASP.net Core REST API 并且总是得到不同的错误:
- “无法访问已处置的对象..”
- “迭代上下文类型查询的结果时发生异常......”
- “在前一个操作完成之前,在此上下文上开始了第二个操作”..
也许你们中的某个人看到了我的错误,或者可以向我解释我做错了什么。
休息API:
// POST api/events
[HttpPost("create")]
public async Task<IActionResult> CreateAsync([FromBody] EventDTO eventDTO)
{
var newEvent = _mapper.Map<Event>(eventDTO);
try
{
await _eventService.CreateEventAsync(newEvent);
return Ok(newEvent);
}
catch (AppException ex)
{
return BadRequest(new { message = ex.Message });
}
}
界面:
public interface IEventService
{
Task<IEnumerable<Event>> GetAllEventsAsync();
Task<Event> GetEventByIDAsync(int id);
Task<IEnumerable<Event>> GetEventByCityAsync(string city);
Task<Event> CreateEventAsync(Event newEvent);
void UpdateEventAsync(Event newEvent, Event existing, int eventId);
void DeleteEventAsync(Event existing);
}
活动服务:
public class EventService : IEventService
{
private MeMeContext _dbContext;
public EventService(MeMeContext dbContext)
{
_dbContext = dbContext;
}
public async Task<Event> CreateEventAsync(Event newEvent)
{
_dbContext.Events.Add(newEvent);
await _dbContext.SaveChangesAsync();
return newEvent;
}
...
}
启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().
SetCompatibilityVersion(CompatibilityVersion.Version_2_2).
AddJsonOptions(opts => opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddDbContext<MeMeContext>(opts => opts.UseNpgsql(Configuration.GetConnectionString(DATABASE)));
services.AddScoped<MeMeContext>();
// configure DI for application services
services.AddScoped<IUserService, UserService>();
services.AddScoped<IEventService, EventService>();
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new AutoMapperProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
...
}
我也不明白的一件事是,当我使用 Visual Studio 或“dotnet run”启动我的应用程序时,我会遇到不同的错误。时常发生的一件事是,当我在 REST API 上执行其他操作时,有时我的代码可以正常工作。
当您需要更多信息时,请询问。我很高兴你能给我的每一个提示:)提前谢谢!
解决方案
您不是在等待异步方法。因此,动作中的代码在该CreateEventAsync
逻辑运行时继续运行。当响应返回时,上下文就消失了,因为它的生命周期就是那个范围。
换句话说,你基本上有一个竞争条件。如果CreateEventAsync
逻辑恰好在响应返回之前完成,那么一切都很好。但是,如果它比返回响应花费的时间更长,那么上下文就消失了(连同您的其他作用域服务),并且您开始抛出异常。
长短,使用await
关键字:
await _eventService.CreateEventAsync(newEvent);
异步与在后台运行某些东西不同。如果您希望该操作能够在此逻辑完成之前返回,那么您应该安排它在后台服务上运行。请参阅:https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio
推荐阅读
- asp.net-web-api - 作为 Azure 应用服务运行时,UserPrincipal.DisplayName 抛出 COMException“访问被拒绝”,在本地开发笔记本电脑上工作正常
- angular - EventEmitter 不断发出值
- laravel - Dompdf 在 laravel 中使用 post 方法返回乱码数据
- html - 导航栏中的行和容器无法正常工作
- html - 导航栏标题不在中心
- android - Fabric crashlytics csyms 不存在
- python - 具有高级约束的 Scipy 投资组合优化
- r - R 在 filter_at 中的starts_with 错误(`starts_with()` 必须在 *selecting* 函数中使用。)
- wordpress - Wordpress:如何编辑有关电子邮件地址更改的邮件?
- android - 错误“未解决的参考:activity_splash”