© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•13mo ago•
22 replies
bati

Cannot access a disposed context instance.

I'm receiving the
ObjectDisposedException
ObjectDisposedException
about a DbContext being disposed while using
IDbContextFactory<>
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();
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();

Exception_Trace.txt8.64KB
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Cannot access non-static method in static context?
C#CC# / help
4y ago
SqlConnection Connection Disposed
C#CC# / help
15mo ago
TcpClient being Disposed
C#CC# / help
2y ago
Blazor Server: Cannot access a closed Stream
C#CC# / help
2y ago