I have a class called StudentDbContext. I call theOnConfiguring method in it. I saw that dependency injection is used in some training videos. Here we already use context once. Why should I use dependency injection instead of OnConfiguring?
Option-1
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("...");
}
Option-2
public StudentDbContext(DbContextOptions<StudentDbContext> context) : base(context)
{
}
CodePudding user response:
protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySQL("..."); }
With this approach, you decide exactly which provider (MySQL) and which connection-string to use within StudentDbContext
directly. If you want to change this to use a different provider or connection-string, you'll have to modify the StudentDbContext
class directly. For example, consider a situation where you want to use a different provider for Development vs Production.
public StudentDbContext(DbContextOptions<StudentDbContext> context) : base(context) { }
This approach allows you to configure both the provider and the connection-string from outside of the StudentDbContext
.
Using Dependency Injection, you'll see something like this in Startup.ConfigureServices
(or Program.cs with ASP .NET Core 6):
services.AddDbContext<StudentDbContext>(options =>
{
options.UseMySQL("...");
});
This second approach becomes more powerful when you want to use different providers/connection-strings (or even other settings) based on an environment, for example:
if (hostEnvironment.IsDevelopment())
{
services.AddDbContext<StudentDbContext>(options =>
{
options.UseMySQL("...");
});
}
else
{
services.AddDbContext<StudentDbContext>(options =>
{
options.UseSqlServer("...");
});
}
CodePudding user response:
With dependency injection the DbContext doesn't need to know about the actual database in use. Furthermore, the DbContext doesn't even need to know which configuration settings should be used for establishing database connections.
This makes your code more independent. This e.g. makes your code more testable. There are other advantages, too.