簡體   English   中英

Asp.net Core:無法訪問已處置的對象(不同的錯誤)

[英]Asp.net Core: Can not access a disposed object (different errors)

我知道這個問題出在很多地方,但是我不得不說,我讀了兩天就能找到的所有內容,但沒有得到我的錯誤。

我創建了一個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 });
        }
    }

接口:

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/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM