简体   繁体   中英

.NET Core SocketIO - Cannot access disposed object

I use SocketIOClientDotNet to get data from a stream ( https://github.com/Quobject/SocketIoClientDotNet ), i then want to save this data to the database;

private readonly DataContext _context;

public SocketIo(DataContext context)
{
    this._context = context;
}

public void SocketStart()
{
    var socket = IO.Socket("myip");

    socket.On("xx", async (data) =>
        {                                                              
            var test = await Update(data.ToString());
        });
}

public async Task<SocketPrice> Update(string data)
{
    SocketPrice socketStream = JsonConvert.DeserializeObject<SocketPrice>(data);

    SocketPrice socketDB = await _context.SocketPrices.Where(s => s.Id == socketStream.Id).FirstOrDefaultAsync();
    socketDB.value = socketStream.value;

    await _context.SaveChangesAsync();   

    return socketDB;
}

When running this from startup;

In configure services; services.AddScoped<ISocketIoService, SocketIo>();

And in configure; socket.SocketStart();

I get the error message;

Unhandled Exception: System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the con text, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposi ng context instances.

When changing the method to synchronous, the method runs but is restarted before it is finished and therefore the results are not saved to the Database. How could i change this setup to save the new incoming data to the database?

Inject IServiceProvider . Resolve the DataContext when you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM