Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2.0: Why doesn't services.AddDbContext accept an interface?

My understanding is that one key advantage of using dependency injection is that you don't tightly bind to types, so you can later swap out pieces of your architecture with less work than otherwise. If that's the case, why is it that I see code like this:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

...
}

The method I'm curious about is:

public static IServiceCollection AddDbContext<TContext>([NotNullAttribute] this IServiceCollection serviceCollection, [CanBeNullAttribute] Action<DbContextOptionsBuilder> optionsAction = null, ServiceLifetime contextLifetime = ServiceLifetime.Scoped, ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) where TContext : DbContext;

So, when I want to access this type, I place an AppDbContext class type in my constructor, not an IAppDbContext interface. But why? Is this too much abstraction? And if so, why bother registering anything to the container with interfaces?

like image 992
BenjiFB Avatar asked Dec 22 '25 14:12

BenjiFB


1 Answers

To resolve this, use one of the overloads having 2 generic type arguments, which allow you to specify both the service interface/class you want to register as well as the DbContext derived class implementing it.

services.AddDbContext<IMyDbContext, MyDbContext>(options =>
     options.UseSqlServer(...));
like image 120
NER1808 Avatar answered Dec 24 '25 02:12

NER1808



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!