ASP.NET Core 2 无法解析 Microsoft EntityFrameworkCore DbContext 类型的服务

编程入门 行业动态 更新时间:2024-10-26 02:25:25
本文介绍了ASP.NET Core 2 无法解析 Microsoft EntityFrameworkCore DbContext 类型的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我运行我的 asp core 2 项目时,我收到以下错误消息:

When I run my asp core 2 projects I get the following error message:

InvalidOperationException:尝试激活ContosoUniversity.Service.Class.StudentService"时无法解析Microsoft.EntityFrameworkCore.DbContext"类型的服务.

InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'ContosoUniversity.Service.Class.StudentService'.

这是我的项目结构:

-- solution 'ContosoUniversity' ----- ContosoUniversity ----- ContosoUniversity.Model ----- ContosoUniversity.Service

IEntityService(相关代码):

public interface IEntityService<T> : IService where T : BaseEntity { Task<List<T>> GetAllAsync(); }

IEntityService(相关代码):

public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity { protected DbContext _context; protected DbSet<T> _dbset; public EntityService(DbContext context) { _context = context; _dbset = _context.Set<T>(); } public async virtual Task<List<T>> GetAllAsync() { return await _dbset.ToListAsync<T>(); } }

实体:

public abstract class BaseEntity { } public abstract class Entity<T> : BaseEntity, IEntity<T> { public virtual T Id { get; set; } }

学生服务:

public interface IStudentService : IEntityService<Student> { Task<Student> GetById(int Id); }

学生服务:

public class StudentService : EntityService<Student>, IStudentService { DbContext _context; public StudentService(DbContext context) : base(context) { _context = context; _dbset = _context.Set<Student>(); } public async Task<Student> GetById(int Id) { return await _dbset.FirstOrDefaultAsync(x => x.Id == Id); } }

学校环境:

public class SchoolContext : DbContext { public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { } public DbSet<Course> Courses { get; set; } public DbSet<Enrollment> Enrollments { get; set; } public DbSet<Student> Students { get; set; } }

最后是我的 Startup.cs 类:

public class Startup { public Startup(IConfiguration configuration, IHostingEnvironment env, IServiceProvider serviceProvider) { Configuration = configuration; var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); Configuration = builder.Build(); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<SchoolContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped<IStudentService, StudentService>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }

我应该怎么做才能解决这个问题?

What should I do to resolve this problem?

推荐答案

StudentService 期望 DbContext 但容器不知道如何根据您当前的启动来解决它.

StudentService expects DbContext but the container does not know how to resolve it based on your current startup.

您需要将上下文显式添加到服务集合中

You would need to either explicitly add the context to the service collection

启动

services.AddScoped<DbContext, SchoolContext>(); services.AddScoped<IStudentService, StudentService>();

或更新 StudentService 构造函数以明确期望容器知道如何解析的类型.

Or update the StudentService constructor to explicitly expect a type the container knows how to resolve.

学生服务

public StudentService(SchoolContext context) : base(context) { //... }

更多推荐

ASP.NET Core 2 无法解析 Microsoft EntityFrameworkCore DbContext 类型的服务

本文发布于:2023-11-17 04:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608830.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Core   NET   ASP   DbContext

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!