Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between configuring connection in a DbContext with OnConfiguring() or Services.AddDbContext() in a .NET Core Web API project?

I am building a REST API using .NET Core with Entity Framework and I am unsure about the differences of the following two approaches.

Option 1

In a class that implements DbContext, I can configure the connection in the OnConfiguring() method like so:

public class GameContext : DbContext
{
    public GameContext(DbContextOptions<GameContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer("DbConnectionString");
    }

    public DbSet<Game> Games { get; set; }
}

Option 2

Alternatively, I can configure the connection in Program.cs using Services.AddDbContext() like so:

builder.Services.AddDbContext<GameContext>(options => options.UseSqlServer("DbConnectionString"));

Can someone please explain the difference between these two approaches? Like:

  • Are there any performance differences between using OnConfiguring() and Services.AddDbContext()?
  • In what situations might one approach be more appropriate than the other?
like image 349
Daniel Shelestov Avatar asked Sep 03 '25 02:09

Daniel Shelestov


1 Answers

Both options do essentially the same thing.
https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#dbcontextoptions

However option 2 is only executed once on application start, so it's considered a good practice to set the connection string here, assuming it's not subject to change during runtime.
Using this approach you will also be able to store and access your connection string from appsettings.json:
string? connectionString = builder.Configuration.GetConnectionString("Default");

Option 1 will execute each time a new instance of DbContext is created, which usually happens when a new instance of your service classes is needed (e.g GameService). This method is called even if you previously used AddDbContext, making it a good place for additional configurations.
See service lifetimes:
https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#service-lifetimes

Performance-wise it has little to no impact (as a simple stopwatch test, this may not be accurate):

  • in Program.cs: ~0.5ms
  • in GameContext: ~0.1ms
like image 102
TacticalCamel Avatar answered Sep 05 '25 19:09

TacticalCamel