首页 > 解决方案 > 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 上执行其他操作时,有时我的代码可以正常工作。

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

标签: c#entity-frameworkasp.net-core

解决方案


您不是在等待异步方法。因此,动作中的代码在该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


推荐阅读