You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用using指令与SQLite遇ObjectDisposedException及DI注入问题咨询

Hey there, let's break down your two issues one by one:

1. ObjectDisposedException with SQLite Context & Using Blocks

Your problem boils down to EF Core's lazy execution/lazy loading behavior. The context.FooTable you're assigning to allResults isn't actually a collection of data—it's just a query "blueprint". EF Core only runs the query against the database when you try to enumerate the result (like calling ToList(), looping through it, or when it gets serialized after being returned).

But since you wrapped the context in a using block, the block automatically calls context.Dispose() when it exits, releasing the database connection and all associated resources. By the time you try to use allResults later, the context it depends on is already destroyed—hence the ObjectDisposedException.

Your first example works because SaveChanges() is an immediate operation—it runs and completes while the context is still alive inside the using block.

Fixes to avoid the exception:

  • If you need to return actual data: Load the results into memory inside the using block with ToList() (or similar methods that trigger immediate execution):
    List<FooThing> allResults; 
    using (FooContext context = new FooContext()) 
    { 
        allResults = context.FooTable.ToList(); 
    } 
    return allResults;
    
    This pulls the data into an in-memory list, so you don't need the context anymore after the using block closes.
  • If you need a queryable object (to add more filters later): Stop managing the context manually with using. Instead, use dependency injection (the approach you're trying in your second question)—the framework will handle creating and disposing the context correctly for each request, eliminating this kind of error.

2. DI Service Resolution Error for FooContext

You're exactly right—this error happens because you haven't registered FooContext with ASP.NET Core's service container, so the DI system can't find an instance to inject into your FooController.

How to configure it:

  1. First, make sure you have the EF Core SQLite NuGet package installed: Microsoft.EntityFrameworkCore.Sqlite (if you haven't already).
  2. Update your service registration code:
    • For .NET 5 and earlier (in Startup.cs):
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllers();
          // Add this line to register your FooContext
          services.AddDbContext<FooContext>(options =>
              options.UseSqlite(Configuration.GetConnectionString("FooContextConnection")));
      }
      
    • For .NET 6+ (in Program.cs):
      var builder = WebApplication.CreateBuilder(args);
      // Add services to the container.
      builder.Services.AddControllers();
      // Register FooContext here
      builder.Services.AddDbContext<FooContext>(options =>
          options.UseSqlite(builder.Configuration.GetConnectionString("FooContextConnection")));
      
  3. Add your SQLite connection string to appsettings.json:
    "ConnectionStrings": {
        "FooContextConnection": "Data Source=YourDatabaseName.db"
    }
    
    Replace YourDatabaseName.db with your actual SQLite database filename (use a relative or absolute path if it's not in your project root).

Once you set this up, the DI framework will handle creating FooContext instances for your controllers, and automatically dispose them when the request finishes—fixing both the injection error and the manual context management issues from your first problem.

内容的提问来源于stack exchange,提问作者BonEd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:21:25