【问题标题】:How to properly configure the `services.AddDbContext` of `ConfigureServices` method如何正确配置`ConfigureServices`方法的`services.AddDbContext`
【发布时间】:2019-10-25 05:17:22
【问题描述】:

我正在尝试使用 EF Core 运行 .NET Core Web 应用程序。为了测试存储库,我添加了一个 MyDbContext,它继承了 EF DbContext 和接口 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; }
}

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

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:无法解析服务类型 尝试激活“GenericRepository`1[MyModel]”时出现“IMyDbContext”

而当使用这行代码时:

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

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

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

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

【问题讨论】:

  • 添加花括号以消除编译错误
  • 不要使用IMyDbContext
  • 我不会打扰 DbContext 的接口,而是使用 AddDbContext
  • @VidmantasBlazevicius 我需要它来进行单元测试
  • 在内存数据库中用于单元测试

标签: c# .net-core entity-framework-core dbcontext


【解决方案1】:

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

例如:

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

【讨论】:

  • 嘿@Ivan,它看起来像干净和好的答案,但它创建了一个例外:Could not resolve a service of type 'MyDbContext' for the parameter 'modelsDbContext' of method 'Configure' on type 'Startup'. Inner Exception 1: InvalidOperationException: No service for type 'MyDbContext' has been registered.
  • 嗯,以上就是我从 EF Core 的角度所能了解的全部内容。新异常表明您在帖子中未显示的代码中直接依赖于MyDbContext
【解决方案2】:

刚刚找到答案:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-30
    • 2017-05-15
    • 2016-09-05
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多