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

Sha*_*ani 3 c# dbcontext entity-framework-core .net-core

我正在尝试使用 EF Core 运行 .NET Core Web 应用程序。为了测试存储库,我添加了一个MyDbContext继承 EFDbContext和 interface 的IMyDbContext

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

上下文接口被注入到我的通用存储库中:

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

    public GenericRepository(IMyDbContext context)
    {
        this._context = context;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在 startup.cs 上使用此代码(不带接口)时:

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

我收到以下运行时错误:

InvalidOperationException:尝试激活“GenericRepository`1[MyModel]”时无法解析“IMyDbContext”类型的服务

当使用这行代码时:

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

我收到以下编译时间错误代码:

无法将 lambda 表达式转换为类型“ServiceLifetime”,因为它不是委托类型

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

Iva*_*oev 5

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

例如:

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

  • 好了,以上就是我从 EF Core 的角度所能了解到的全部内容。新的异常表明您在帖子中未显示的代码中直接依赖于“MyDbContext”。 (3认同)

Sha*_*ani 5

刚刚找到答案:

IMyDbContext我错过了在和之间添加范围MyDbContext

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