ASP.NET Core 2.0:为什么 services.AddDbContext 不接受接口?

Ben*_*iFB 2 c# asp.net dependency-injection inversion-of-control asp.net-core-2.0

我的理解是,使用依赖注入的一个关键优势是,您不会紧密绑定到类型,因此您以后可以用比其他方式更少的工作来交换架构的各个部分。如果是这样的话,为什么我会看到这样的代码:

// 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")));

...
}
Run Code Online (Sandbox Code Playgroud)

我很好奇的方法是:

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;
Run Code Online (Sandbox Code Playgroud)

因此,当我想访问此类型时,我在构造函数中放置 AppDbContext 类类型,而不是 IAppDbContext 接口。但为什么?这是不是太抽象了?如果是这样,为什么还要用接口向容器注册任何东西呢?

NER*_*808 9

要解决此问题,请使用具有 2 个泛型类型参数的重载之一,它允许您指定要注册的服务接口/类以及实现它的 DbContext 派生类。

services.AddDbContext<IMyDbContext, MyDbContext>(options =>
     options.UseSqlServer(...));
Run Code Online (Sandbox Code Playgroud)