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
- Pass --project and --startup-project explicitly
- Add an IDesignTimeDbContextFactory
- Run with --verbose to see the startup exception
Detailed fix by platform
Shell
dotnet ef migrations add Init --project src/App.Data --startup-project src/App.Api --verbose
C#
- 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
- Projects — Startup vs migrations project
- Verbose — Inner exception
- 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:
Similar errors
Most viewed in .NET
Other ways to find it
🧠 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.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 7 Oct 2026