web-dev-qa-db-fra.com

ASP.NET Core 2 Impossible de résoudre le service pour le type DbContext Microsoft EntityFrameworkCore

Lorsque j'exécute mes projets asp.net core 2, le message d'erreur suivant s'affiche:

InvalidOperationException: Impossible de résoudre le service pour le type 'Microsoft.EntityFrameworkCore.DbContext' lors de l'activation de 'ContosoUniversity.Service.Class.StudentService'.

Voici la structure de mon projet:

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

IEntityService (code associé):

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

IEntityService (code associé):

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

Entité:

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

StudentService:

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

Et enfin voici mon Startup.cs class: 

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

Que dois-je faire pour résoudre ce problème?

5
mohammad

StudentService s'attend à DbContext mais le conteneur ne sait pas comment le résoudre en fonction de votre démarrage actuel.

Vous devrez soit explicitement ajouter le contexte à la collection de services.

Commencez

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

Ou met à jour le constructeur StudentService en prévoyant explicitement un type que le conteneur sait résoudre.

StudentService

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

si dbcontext hérité de system.data.entity. DbContext alors il serait ajouté comme ça

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

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