是否可以在异步定时器中使用 context.Add(object)?

Is it possible to context.Add(object) in asynchronous Timer?

我正在使用 C# ASP.net 并且需要通过异步计时器在我的数据库中创建一个对象。

我的计时器:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Response response = new Response(tweet.Id, 1128199274838282240);

    _context.Add(response);
    _context.SaveChanges();
}

当我调用它时:

Timer timer = new System.Timers.Timer(60000);

timer.Elapsed += OnTimedEvent;
timer.Enabled = true;

当我从控制器创建 class 时,我通过构造函数提供了上下文:

    private readonly cardsagainsttwitterContext _context;

    public GameManager(cardsagainsttwitterContext context)
    {
        _context = context;
    }

当然,我收到此错误是因为上下文不再存在: - System.InvalidOperationException : 'An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.'

那么,是否可以这样做或两者都不做? 感谢阅读!

上下文应存在于时间生命周期内,通常在 Web 应用程序中(根据我的所有建议)请求时间生命周期本身或更短的时间生命周期,如瞬态。

如果计时器在 60 秒后启动,它将没有请求上下文,因为请求已完成(我假设...)并且数据库上下文在其生命周期内处理。

尝试在计时器事件中实例化另一个上下文,并用它来保存您的响应:

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Response response = new Response(tweet.Id, 1128199274838282240);
    using(var timerContext=new cardsagainsttwitterContext())
    {
        timerContext.Add(response);
        timerContext.SaveChanges();
    }
}