C#C
C#12mo ago
bati

Cannot access a disposed context instance.

I'm receiving the ObjectDisposedException about a DbContext being disposed while using IDbContextFactory<> to initialize my database context. After searching online for potential ways for me to approach resolving this, none of them seem to apply for my case.

Code:
logger.LogInformation("{Availability} Guild {Name} has just been created.", $"{(gatewayEvent.Guild.IsT0 ? "A" : "Una")}vailable", gatewayEvent.Guild.IsT0 ? gatewayEvent.Guild.AsT0.Name : gatewayEvent.Guild.AsT1.ID.ToString());
        
if (gatewayEvent.Guild.IsT1) return Result.FromSuccess();

var guild = gatewayEvent.Guild.AsT0;
var guildModel = new GuildModel(guild, configuration["PREFIX"]!);

await using (var databaseContext = await database.CreateDbContextAsync(ct))
{
    var dbGuild = await databaseContext.Guilds.SingleByIdAsync(guild.ID, ct);
            
    if (dbGuild is null) // Only add actual new guilds to the database as this fires on ALL guilds during startup
    {
        databaseContext.Guilds.Add(guildModel);
        await databaseContext.SaveChangesAsync(ct);
    } else guildModel = dbGuild;
}

using (var entry = memoryCache.CreateEntry(CacheKey.StringKey($"Guild:{guild.ID}")))
    entry.Value = guildModel;
        
return Result.FromSuccess();

Was this page helpful?