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?
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(...));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With