Unable to create a 'DbContext' 🟪 .NET

dotnet ef: Unable to create a 'DbContext' of type ''. The exception 'Unable to resolve service for type DbContextOptions' was thrown while attempting to create an instance

dotnet ef migrations couldn’t construct your DbContext at design time.

Seen on: .NET

Meaning

The tools build the startup project and resolve the context from its host or a factory. Wrong --startup-project, a host that fails to start (missing config), or a context in a class library without a factory cause this.

Common causes

  • Wrong startup project/working directory
  • App host throws at startup (missing config/secrets)
  • Context in a separate library without IDesignTimeDbContextFactory
  • Multiple contexts without --context

⚡ Quick fix

  1. Pass --project and --startup-project explicitly
  2. Add an IDesignTimeDbContextFactory
  3. Run with --verbose to see the startup exception

Detailed fix by platform

Shell

  1. dotnet ef migrations add Init --project src/App.Data --startup-project src/App.Api --verbose

C#

  1. csharp
    public class AppDbFactory : IDesignTimeDbContextFactory<AppDb>
    {
        public AppDb CreateDbContext(string[] args) =>
            new(new DbContextOptionsBuilder<AppDb>().UseSqlServer("Server=.;Database=App;Trusted_Connection=True;TrustServerCertificate=True").Options);
    }

How to diagnose

  1. Projects — Startup vs migrations project
  2. Verbose — Inner exception
  3. Contexts — More than one?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.