.net-core - InvalidOperationException:无法使用 EF dbcontext 解析类型的服务
问题描述
我正在尝试对数据库上下文使用依赖注入。我不确定我做错了什么,但即使按照所有步骤我仍然得到错误
以下是我遵循的步骤,建议我哪里出错了。我正在使用多层项目,因此我的存储库位于我的数据库访问层和 mvc api 应用程序中的控制器中
我的数据库上下文类
public partial class TestDbContext: DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options)
: base(options)
{
}
public virtual DbSet<Table1> Table1{ get; set; }
}
public interface IRepository<T> where T : class
{
IQueryable<T> GetDbSet();
}
public class Repository<T> : IRepository<T> where T : class
{
protected DbContext _entities;
protected readonly DbSet<T> _dbset;
public Repository(DbContext context)
{
_entities = context;
_dbset = context.Set<T>();
}
public virtual IQueryable<T> GetDbSet()
{
return _dbset;
}
}
pulbic interface IUserRepository
{
List<UsersInfo> GetUsers();
}
public class UserRepository:IUserRepository
{
private readonly IRepository<Table1> table1repo;
public UserRepository(IRepository<Table1> _table1Repo)
{
table1repo = _table1Repo;
}
public List<UsersInfo> GetUsers()
{
return table1repo.GetDbSet().ToList();
}
}
public class MyController : : ControllerBase
{
private readonly IUserRepository _UserRepo;
public MyController (IUserRepository UserRepo)
{
_UserRepo= clientInfo;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
var result = _UserRepo.GetUsers();
return new JsonResult(result) { SerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented } };
}
catch(Exception e)
{
throw e;
}
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.AddDbContext<TestDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
解决方案
您的存储库类中的上下文类型应该是 TestDbContext 而不是 DbContext。
public class Repository<T> : IRepository<T> where T : class
{
protected TestDbContext _entities;
protected readonly DbSet<T> _dbset;
public Repository(TestDbContext context)
{
_entities = context;
_dbset = context.Set<T>();
}
public virtual IQueryable<T> GetDbSet()
{
return _dbset;
}
}
推荐阅读
- vue.js - vue访问图片
- ios - MongoSwift Pod 包含 100 个编译器错误。安装后无法构建
- javascript - WebGL,gl 矩阵。如何从相机视图和投影矩阵中获取截锥体顶点?
- javascript - 选择时间后我不确定
- dart - 如何在字符串中按此名称获取属性?
- r - 在循环中附加列表(R)
- reactjs - 如何将此函数转换为状态为包含网格项的数组的类?
- python - 跳过 bidirectional_dynamic_rnn 中的值
- mysql - 搜索从 MySQL 数据库中的 PDF 中提取的大量文本的列的最佳选择是什么?
- google-chrome - Chrome上的浮动问题