如何正确配置 `ConfigureServices` 方法的 `services.AddDbContext`

How to properly configure the `services.AddDbContext` of `ConfigureServices` method

我正在尝试 运行 带有 EF Core 的 .NET Core Web 应用程序。为了测试存储库,我添加了一个继承 EF DbContext 和接口 IMyDbContext.

MyDbContext
public interface IMyDbContext
{
    DbSet<MyModel> Models { get; set; }
}

public class MyDbContext : DbContext, IMyDbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    public virtual DbSet<MyModel> Models { get; set; }
}

上下文接口已注入我的通用存储库:

public class GenericRepository<TEntity> : IGenericRepository<TEntity>
{
    private readonly IMyDbContext _context = null;

    public GenericRepository(IMyDbContext context)
    {
        this._context = context;
    }
}

当我在 startup.cs 上使用此代码(没有界面)时:

services.AddDbContext<MyDbContext>(options =>
     options.UseSqlServer(...));

我收到 运行 时间错误:

InvalidOperationException: Unable to resolve service for type 'IMyDbContext' while attempting to activate 'GenericRepository`1[MyModel]'

而当使用这行代码时:

services.AddDbContext<IMyDbContext>(options =>
     options.UseSqlServer(...));

我得到这个编译时间错误代码:

Cannot convert lambda expression to type 'ServiceLifetime' because it is not a delegate type

我的问题是如何正确配置ConfigureServices方法的services.AddDbContextConfigure 方法内部是否需要任何更改?) 如果需要,我愿意修改 IMyDbContext

使用具有 2 个通用类型参数的 overloads 之一,它允许您指定要注册的服务 interface/class 以及 DbContext 派生的 class 实施它。

例如:

services.AddDbContext<IMyDbContext, MyDbContext>(options =>
     options.UseSqlServer(...));

刚刚找到答案:

我错过了在 IMyDbContextMyDbContext 之间添加的范围。

public void ConfigureServices(IServiceCollection services)
{                    
    services.AddDbContext<MyDbContext>(options => options.UseSqlServer(...));
    services.AddScoped<IGenericRepository<MyModel>, GenericRepository<MyModel>>();
    services.AddScoped<IMyDbContext, MyDbContext>();
}