EntityFrameworkCore
DbContextOptions
DependencyInjection
ASP.NETCore
LibraryContext

'Unable to resolve service for type ¨Microsoft.entityFrameworkCore.DbContextOptions¨1LibraryData.LibraryContext while attempting to activate

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The error Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions'1[LibraryData.LibraryContext]' while attempting to activate means your DbContext was not registered in the ASP.NET Core dependency injection container. The DI system cannot provide the DbContextOptions<LibraryContext> that Entity Framework Core needs to construct your context. The fix is to call AddDbContext<LibraryContext>() in your Program.cs (or Startup.cs in older templates).

The Error

 
System.InvalidOperationException: Unable to resolve service for type
'Microsoft.EntityFrameworkCore.DbContextOptions`1[LibraryData.LibraryContext]'
while attempting to activate 'LibraryData.LibraryContext'.

This occurs when a controller or service requests LibraryContext via constructor injection, but the DI container has no registration for it.

The Fix

.NET 6+ (Minimal API / Program.cs)

csharp
1var builder = WebApplication.CreateBuilder(args);
2
3// Register the DbContext — THIS IS THE FIX
4builder.Services.AddDbContext<LibraryContext>(options =>
5    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
6);
7
8var app = builder.Build();

.NET 5 and Earlier (Startup.cs)

csharp
1public class Startup
2{
3    public void ConfigureServices(IServiceCollection services)
4    {
5        // Register the DbContext
6        services.AddDbContext<LibraryContext>(options =>
7            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
8        );
9
10        services.AddControllers();
11    }
12}

The DbContext Class

csharp
1// LibraryData/LibraryContext.cs
2using Microsoft.EntityFrameworkCore;
3
4namespace LibraryData
5{
6    public class LibraryContext : DbContext
7    {
8        // This constructor is REQUIRED for DI
9        public LibraryContext(DbContextOptions<LibraryContext> options)
10            : base(options)
11        {
12        }
13
14        public DbSet<Book> Books { get; set; }
15        public DbSet<Author> Authors { get; set; }
16    }
17}

Common Cause 1: Missing AddDbContext Call

The most frequent cause. You created the DbContext class but forgot to register it in the DI container.

csharp
1// BROKEN — no DbContext registration
2var builder = WebApplication.CreateBuilder(args);
3builder.Services.AddControllers();
4// Missing: builder.Services.AddDbContext<LibraryContext>(...)
5var app = builder.Build();
6
7// FIXED
8var builder = WebApplication.CreateBuilder(args);
9builder.Services.AddDbContext<LibraryContext>(options =>
10    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
11);
12builder.Services.AddControllers();
13var app = builder.Build();

Common Cause 2: Wrong DbContextOptions Type

The constructor must accept DbContextOptions<LibraryContext> (generic), not DbContextOptions (non-generic).

csharp
1// BROKEN — uses non-generic DbContextOptions
2public class LibraryContext : DbContext
3{
4    public LibraryContext(DbContextOptions options)  // Wrong type
5        : base(options) { }
6}
7
8// FIXED — uses generic DbContextOptions<LibraryContext>
9public class LibraryContext : DbContext
10{
11    public LibraryContext(DbContextOptions<LibraryContext> options)
12        : base(options) { }
13}

The DI container registers DbContextOptions<LibraryContext> specifically, so asking for the non-generic DbContextOptions will not match.

Common Cause 3: Missing Constructor

If your DbContext has a parameterless constructor or no constructor at all, EF Core cannot inject the options.

csharp
1// BROKEN — no constructor accepting options
2public class LibraryContext : DbContext
3{
4    // EF Core has no way to pass options in
5    public DbSet<Book> Books { get; set; }
6}
7
8// BROKEN — parameterless constructor only
9public class LibraryContext : DbContext
10{
11    public LibraryContext() { }
12    public DbSet<Book> Books { get; set; }
13}
14
15// FIXED — constructor accepts options
16public class LibraryContext : DbContext
17{
18    public LibraryContext(DbContextOptions<LibraryContext> options)
19        : base(options) { }
20
21    public DbSet<Book> Books { get; set; }
22}

Common Cause 4: Connection String Missing

AddDbContext is called, but the connection string is null or missing from appsettings.json.

json
1// appsettings.json
2{
3  "ConnectionStrings": {
4    "DefaultConnection": "Server=localhost;Database=LibraryDb;Trusted_Connection=True;"
5  }
6}
csharp
1// This returns null if "DefaultConnection" is not in appsettings.json
2var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
3
4// AddDbContext still registers the context, but it will fail at runtime
5// when trying to connect to the database
6builder.Services.AddDbContext<LibraryContext>(options =>
7    options.UseSqlServer(connectionString)
8);

Common Cause 5: Multiple DbContexts

When you have multiple DbContext classes, each must be registered separately.

csharp
1public class LibraryContext : DbContext { /* ... */ }
2public class IdentityContext : DbContext { /* ... */ }
3
4// Must register BOTH
5builder.Services.AddDbContext<LibraryContext>(options =>
6    options.UseSqlServer(builder.Configuration.GetConnectionString("LibraryDb"))
7);
8builder.Services.AddDbContext<IdentityContext>(options =>
9    options.UseSqlServer(builder.Configuration.GetConnectionString("IdentityDb"))
10);

Using Different Database Providers

csharp
1// SQL Server
2builder.Services.AddDbContext<LibraryContext>(options =>
3    options.UseSqlServer(connectionString)
4);
5
6// PostgreSQL (Npgsql)
7builder.Services.AddDbContext<LibraryContext>(options =>
8    options.UseNpgsql(connectionString)
9);
10
11// SQLite
12builder.Services.AddDbContext<LibraryContext>(options =>
13    options.UseSqlite("Data Source=library.db")
14);
15
16// In-Memory (for testing)
17builder.Services.AddDbContext<LibraryContext>(options =>
18    options.UseInMemoryDatabase("TestDb")
19);

Injecting the Context

Once registered, inject LibraryContext via constructor injection:

csharp
1public class BooksController : ControllerBase
2{
3    private readonly LibraryContext _context;
4
5    public BooksController(LibraryContext context)
6    {
7        _context = context;
8    }
9
10    [HttpGet]
11    public async Task<ActionResult<IEnumerable<Book>>> GetBooks()
12    {
13        return await _context.Books.ToListAsync();
14    }
15}

You can also inject into services:

csharp
1public class BookService
2{
3    private readonly LibraryContext _context;
4
5    public BookService(LibraryContext context)
6    {
7        _context = context;
8    }
9}
10
11// Register the service
12builder.Services.AddScoped<BookService>();

Common Pitfalls

  • Registering AddDbContext after Build(): AddDbContext must be called before builder.Build(). Any service registration after Build() has no effect and the context will not be found.
  • Using new LibraryContext() instead of DI: Manually constructing the context bypasses DI and loses connection string configuration. Always inject the context through constructors.
  • Wrong project reference: If LibraryContext is in a separate class library project (e.g., LibraryData), ensure the web project references that project and the correct NuGet packages (Microsoft.EntityFrameworkCore.SqlServer) are installed in the right project.
  • Service lifetime mismatch: AddDbContext registers the context as Scoped by default. Injecting a scoped service into a singleton causes a runtime error. If you need a context in a singleton, use IServiceScopeFactory to create a scope.
  • Confusing AddDbContext with AddDbContextFactory: AddDbContextFactory<T> (EF Core 5+) registers a factory, not the context directly. Injecting LibraryContext directly will fail — you must inject IDbContextFactory<LibraryContext> and call CreateDbContext().

Summary

  • Call AddDbContext<LibraryContext>(options => ...) in Program.cs or Startup.ConfigureServices
  • The DbContext must have a constructor accepting DbContextOptions<LibraryContext> (generic version)
  • Ensure the connection string exists in appsettings.json under ConnectionStrings
  • Register each DbContext separately when using multiple contexts
  • The context is Scoped by default — do not inject directly into singleton services

Course illustration
Course illustration

All Rights Reserved.