C# Asp.net Core:无法访问已处置的对象(不同错误)

C# Asp.net Core:无法访问已处置的对象(不同错误),c#,entity-framework,asp.net-core,C#,Entity Framework,Asp.net Core,我知道这个问题在这里很多,但我不得不说我读了我能找到的所有东西,读了大约两天,没有发现我的错误 我创建了一个ASP.net Core REST API,并始终收到不同的错误: “无法访问已处置的对象..” “迭代查询结果时发生异常 对于上下文类型..” “在上一个操作之前,在此上下文上启动了第二个操作 “操作已完成” 也许你们中的某个人看到了我的错误,或者可以向我解释,我做错了什么 Rest API: // POST api/events [HttpPost("create")]

我知道这个问题在这里很多,但我不得不说我读了我能找到的所有东西,读了大约两天,没有发现我的错误

我创建了一个ASP.net Core REST API,并始终收到不同的错误:

  • “无法访问已处置的对象..”
  • “迭代查询结果时发生异常 对于上下文类型..”
  • “在上一个操作之前,在此上下文上启动了第二个操作 “操作已完成”
也许你们中的某个人看到了我的错误,或者可以向我解释,我做错了什么

Rest 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 });
        }
    }
//发布api/事件
[HttpPost(“创建”)]
公共异步任务CreateAsync([FromBody]EventDTO到EventDTO)
{
var newEvent=_mapper.Map(eventDTO);
尝试
{
wait\u eventService.CreateEventAsync(newEvent);
返回Ok(newEvent);
}
捕获(外观例外)
{
返回BadRequest(新的{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);
}
公共接口IEventService
{
任务GetAllEventsAsync();
任务GetEventByIDAsync(int-id);
任务GetEventByCityAsync(字符串城市);
任务CreateEventAsync(事件newEvent);
void UpdateEventAsync(Event newEvent、Event existing、int eventId);
void DeleteEventAsync(事件存在);
}
事件服务:

 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;
    }
    ...
}
公共类事件服务:IEventService
{
私有MeMeContext _dbContext;
公共事件服务(MeMeContext dbContext)
{
_dbContext=dbContext;
} 
公共异步任务CreateEventAsync(Event newEvent)
{
_dbContext.Events.Add(newEvent);
wait_dbContext.saveChangesSync();
返回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);
    ...
}
public void配置服务(IServiceCollection服务)
{
services.AddCors();
services.AddMvc()。
SetCompatibilityVersion(CompatibilityVersion.Version_2_2)。
AddJsonOptions(opts=>opts.SerializerSettings.ReferenceLoopHandling=ReferenceLoopHandling.Ignore);
services.AddDbContext(opts=>opts.UseNpgsql(Configuration.GetConnectionString(数据库));
services.addScope();
//为应用程序服务配置DI
services.addScope();
services.addScope();
var mappingConfig=新的MapperConfiguration(mc=>
{
mc.AddProfile(新的AutoMapperProfile());
});
IMapper mapper=mappingConfig.CreateMapper();
服务。AddSingleton(映射器);
...
}
还有一件事我也不明白,当我用Visual Studio或“dotnet run”启动我的应用程序时,我会遇到不同的错误。有时也会发生一件事,当我在RESTAPI上做其他事情时,我的代码有时会工作

当你需要更多信息时,尽管问。我很高兴你能给我的每一个暗示:)
提前谢谢

您没有等待异步方法。因此,当
CreateEventAsync
逻辑运行时,操作中的代码将继续运行。当响应返回时,上下文就消失了,因为它的生存期就是这个范围

换句话说,你基本上有一个竞赛条件。如果
CreateEventAsync
逻辑恰好在响应返回之前完成,则一切正常。但是,如果返回响应所需的时间比返回响应所需的时间长,则上下文(以及其他作用域服务)将消失,并且您将开始抛出异常

长和短,使用
wait
关键字:

await _eventService.CreateEventAsync(newEvent);

异步与在后台运行不同。如果您希望操作能够在该逻辑完成之前返回,那么应该将其安排在后台服务上运行。请参阅:

您没有在等待异步方法。因此,当
CreateEventAsync
逻辑运行时,操作中的代码将继续运行。当响应返回时,上下文就消失了,因为它的生存期就是这个范围

换句话说,你基本上有一个竞赛条件。如果
CreateEventAsync
逻辑恰好在响应返回之前完成,则一切正常。但是,如果返回响应所需的时间比返回响应所需的时间长,则上下文(以及其他作用域服务)将消失,并且您将开始抛出异常

长和短,使用
wait
关键字:

await _eventService.CreateEventAsync(newEvent);

异步与在后台运行不同。如果您希望操作能够在该逻辑完成之前返回,那么应该将其安排在后台服务上运行。请参阅:

哪一行产生了错误?@TKK它是在“awaitdbContext.savechangesync();”行产生的。哪一行产生了错误?@TKK它是在“awaitdbContext.savechangesync();”行产生的。我添加了你的想法(在我感到非常愚蠢之后),但我又出现了第三个错误。(此上下文中的第二个操作开始…)您可能还有另一个不在某处等待的实例。Jip您是对的。。哦,老兄,这真令人沮丧。。但是非常感谢你!有两件事可以帮助你。首先,在末尾命名您使用
async
创建的任何异步方法。然后,对于在末尾具有
Async
的任何方法,您应该在其前面添加
wait
。当然也有例外,但是你需要wait的情况要比你不需要的情况普遍得多,当你不需要wait的时候,应该有一个充分的理由让你知道。我想我需要阅读一些关于wait/async的东西,才能完全理解它。我添加了你的想法(在我觉得自己很愚蠢之后),但我又犯了第三个错误。(此上下文中的第二个操作开始…)您可能还有另一个不在某处等待的实例。Jip您是对的。。哦,老兄,这真令人沮丧。。但是非常感谢你!有两件事可以帮助你。首先,在末尾命名您使用
async
创建的任何异步方法。然后,对于任何具有
Async
a