Explore the OnConfiguring Method in EF Core
Introduction
When working with EF (Entity Framework) Core, developers often create a class that derives from DbContext
to represent your application's data model.
Moreover, in this class, developers may override or come across a method called. OnConfiguring
. It is sometimes confusing developers for its proper use cases or purpose.
This article will explore the OnConfiguring
technique, its typical use cases, and its relationship with dependency injection.
What is the OnConfiguring
Method?
From the class,
you have created (let's say CustomerDbContext
)that derives from DbContext
the OnConfiguring
method is a virtual method provided by EF Core.
The primary purpose of it is to configure the database connection and other options for the context.
The behavior of EF when it wants to access a database, checks whether the OnConfiguring
the method has been overridden in the derived context class.
Then, if it has, EF uses the provided configuration.
Then, if not, EF relies on the configuration provided elsewhere, such as through dependency injection.
Let's try to look at a basic example:
using Microsoft.EntityFrameworkCore;
namespace ConsoleApp1.Data
{
public class CustomerDbContext : DbContext
{
public CustomerDbContext() { }
public DbSet<Customer> Customer { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//Your connectionstrings here
optionsBuilder.UseSqlServer("Server=localhost;Database=CustomerDb;Integrated Security=true;Encrypt=false");
}
}
}
}
In this example, we're configuring EF to use a SQL Server database with a connection string (hardcoded).
However, this method is typically practiced when developers work in a scenario where you don't have a DI (Dependency Injection) container to handle your database configuration.
Use Cases for OnConfiguring Method
Again, the primary use case for the OnConfiguring
method is when developers build an application like a console or a desktop application that doesn't rely on dependency injection. Moreover, when developers don't have a service container to manage your database context's configuration in these scenarios.
Instead, you can use OnConfiguring
to provide the necessary configuration directly in your context class.
See the code snippet below.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
//Your connectionstrings here
optionsBuilder.UseSqlServer("Server=localhost;Database=CustomerDb;Integrated Security=true;Encrypt=false");
}
}
Console Application
In console applications, there's often no built-in dependency injection container. Developers may need to use the OnConfiguring
method to set up your database context, including the connection string and other options.
WinForms Applications
Like console applications, WinForms applications typically don't provide a built-in dependency injection system.
Therefore, you can use OnConfiguring
it to configure your database context.
ASP.NET Core Configuration
While ASP.NET Core applications use DI (Dependency Injection), the OnConfiguring
method can still be helpful in specific scenarios.
For example, during the application startup, you might use OnConfiguring
it if you want to access the configuration settings to configure your database context or make the connection strings hardcoded.
But this is not recommended, usually for quick fixes or demonstration purposes only.
Dependency Injection and Database Configuration
In today's modern application development, especially within the ASP.NET Core framework, DI (Dependency Injection) is the preferred way. 👍
Of course, devs love DI to configure and manage services, including database contexts. One reason is that DI (Dependency Injection) containers provide a clean and maintainable approach to setting up your application's services, including your database context. Moreover, devs configure your database context and provide the necessary options at the application's startup.
Here's how it works:
- You register your database context as a service in your application. You can use your application's configuration system to fetch the necessary settings, such as the connection string.
builder.Services.AddDbContext<CustomerDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
But, of course, devs need some adjustments to their DbContext
class (need to overload the constructor).
This is due to the DbContextOptions
that was passed during the service registration.
using Microsoft.EntityFrameworkCore;
namespace WebApplication2.Data
{
public class CustomerDbContext : DbContext
{
public CustomerDbContext(DbContextOptions<CustomerDbContext> context) : base(context) { }
public DbSet<Customer> Customer { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//this will be equal to true therefore no longer needed
if (!optionsBuilder.IsConfigured)
{
//Your connectionstrings here no longer needed
}
}
}
}
- The dependency injection container takes care of creating and configuring the database context. You can inject it into your controllers, services, or other application parts.
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebApplication2.Data;
namespace WebApplication2.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly CustomerDbContext _context;
public IndexModel(ILogger<IndexModel> logger, CustomerDbContext customerDbContext)
{
_logger = logger;
_context = customerDbContext;
}
public void OnGet()
{
var customers = _context.Customer.ToList();
}
}
}
Summary
The OnConfiguring
method in Entity Framework Core provides a way to configure the database context directly within the context class when you're not using dependency injection. It's helpful in the console and WinForms applications where a built-in dependency injection container is unavailable.
However, in modern application development, especially with ASP.NET Core, dependency injection is the preferred approach for configuring and managing your database context, making the OnConfiguring
method less commonly used.
Using dependency injection provides a cleaner and more maintainable way to set up and use your database context in your application.
I hope you have enjoyed this article, as I enjoyed it while writing. Till next time, happy cloud computing and programming!