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

moh*_*mad 10 c# dependency-injection asp.net-core-mvc asp.net-core asp.net-core-2.0

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

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

这是我的项目结构:

-- solution 'ContosoUniversity'
----- ContosoUniversity
----- ContosoUniversity.Model
----- ContosoUniversity.Service
Run Code Online (Sandbox Code Playgroud)

IEntityService(相关代码):

public interface IEntityService<T> : IService
 where T : BaseEntity
{
    Task<List<T>> GetAllAsync();      
}
Run Code Online (Sandbox Code Playgroud)

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

实体 :

public abstract class BaseEntity { 

}

public abstract class Entity<T> : BaseEntity, IEntity<T> 
{
    public virtual T Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

IStudentService:

public interface IStudentService : IEntityService<Student>
{
    Task<Student> GetById(int Id);
}
Run Code Online (Sandbox Code Playgroud)

学生服务:

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

学校内容:

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

最后这是我的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?}");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nko*_*osi 26

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

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

启动

services.AddScoped<DbContext, SchoolContext>();
services.AddScoped<IStudentService, StudentService>();
Run Code Online (Sandbox Code Playgroud)

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

StudentService

public StudentService(SchoolContext context)
    : base(context)
{ 
    //...
}
Run Code Online (Sandbox Code Playgroud)


sal*_*man 6

我遇到了类似的错误,即

处理请求时发生未处理的异常。InvalidOperationException:尝试激活“MyProjectName.Controllers.MyUsersController”时无法解析类型“MyProjectName.Models.myDatabaseContext”的服务。

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型 type,类型 requiredBy,bool isDefaultParameterRequired)

我后来发现......我错过了以下行,即将我的数据库上下文添加到服务中:

services.AddDbContext<yourDbContext>(option => option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));
Run Code Online (Sandbox Code Playgroud)

这是我在 Startup 类中定义的 ConfigureServices 方法:

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential 
                //cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<yourDbContext>(option => 
            option.UseSqlServer("Server=Your-Server-Name\\SQLExpress;Database=yourDatabaseName;Trusted_Connection=True;"));

                }
        ...
        ...
    }
Run Code Online (Sandbox Code Playgroud)

基本上,当您从数据库生成模型类时,通过创建“新脚手架项”并在脚手架过程中选择适当的数据库上下文,所有数据库表都会映射到相应的模型类。services现在,您需要手动将数据库上下文注册为方法参数的服务ConfigureServices

顺便说一句,您最好从配置数据中获取连接字符串,而不是对连接字符串进行硬编码。我在这里试图让事情变得简单。