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

时间:2017-09-20 10:56:15

标签: c# dependency-injection asp.net-core asp.net-core-mvc asp.net-core-2.0

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

  

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

这是我的项目结构:

-- 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; }
}

IStudentService:

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);
    }
}

SchoolContext:

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?}");
        });
    }
}

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

4 个答案:

答案 0 :(得分:18)

StudentService预计DbContext,但容器根据您当前的启动情况不知道如何解决它。

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

启动

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

更新StudentService构造函数,以明确指望容器知道如何解析的类型。

StudentService

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

答案 1 :(得分:1)

如果dbcontext是从system.data.entity继承的。 DbContext ,那么它将像这样添加

    services.AddScoped(provider => new CDRContext());

    services.AddTransient<IUnitOfWork, UnitOfWorker>();
    services.AddTransient<ICallService, CallService>();

答案 2 :(得分:0)

我遇到了类似的错误,即

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

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

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

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

这是我在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;"));

                }
        ...
        ...
    }

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

顺便说一句,理想情况下,您将从配置数据中选择它,而不是对连接字符串进行硬编码。我试图在这里简化事情。

答案 3 :(得分:0)

当 options 参数为 null 或无法使用 GetConnectionString() 检索时,将引发此错误。

我遇到这个错误是因为定义我的 ConnectionStrings 的 appsettings.json 文件末尾有一个额外的大括号 }。

愚蠢,但令人沮丧。