【发布时间】: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.AddDbContext的ConfigureServices方法?
(Configure 方法内部是否需要进行任何更改?)
如果需要,我愿意修改 IMyDbContext
【问题讨论】:
-
添加花括号以消除编译错误
-
不要使用
IMyDbContext -
我不会打扰 DbContext 的接口,而是使用 AddDbContext
-
@VidmantasBlazevicius 我需要它来进行单元测试
-
在内存数据库中用于单元测试
标签: c# .net-core entity-framework-core dbcontext