Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType:

I am trying to do a School Management System for practising. But I’m getting exception that i didnt know how to resolve.

Exception That i’m getting;

System.AggregateException: ‘Some services are not able to be constructed (Error while validating the service descriptor ‘ServiceType: SchoolManagementApp.Core.UnitOfWorks.IUnitOfWork Lifetime: Scoped ImplementationType: SchoolManagementApp.Dal.UnitOfWorks.UnitOfWork’: Unable to resolve service for type ‘SchoolManagementApp.Dal.AppDbContext’ while attempting to activate ‘SchoolManagementApp.Dal.UnitOfWorks.UnitOfWork’.) (Error while validating the service descriptor ‘ServiceType: SchoolManagementApp.Core.Repositories.IStudentRepository Lifetime: Scoped ImplementationType: SchoolManagementApp.Dal.Repositories.StudentRepository’: Unable to resolve service for type ‘SchoolManagementApp.Dal.AppDbContext’ while attempting to activate ‘SchoolManagementApp.Dal.Repositories.StudentRepository’.) (Error while validating the service descriptor ‘ServiceType: SchoolManagementApp.Core.Services.IStudentService Lifetime: Scoped ImplementationType: SchoolManagementApp.Service.Services.StudentService’: Unable to resolve service for type ‘SchoolManagementApp.Dal.AppDbContext’ while attempting to activate ‘SchoolManagementApp.Dal.Repositories.GenericRepository`1[SchoolManagementApp.Core.Models.Student]’.)’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddScoped(typeof(IService<>), typeof(Service<>));
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddScoped<IStudentRepository, StudentRepository>();
builder.Services.AddScoped<IStudentService, StudentService>();



var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

AppDbContext.cs

namespace SchoolManagementApp.Dal
{
    public class AppDbContext : DbContext
    {
        public AppDbContext()
        {
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Lesson> Lessons { get; set; }
        public DbSet<Lecturer> Lecturers { get; set; }
        public DbSet<LessonOfStudent> LessonOfStudents { get; set; }
        public DbSet<ActiveLesson> ActiveLessons { get; set; }
        public DbSet<CollegeDepartment> CollegeDepartments { get; set; }
        public DbSet<CollegeDepartmentsActiveLesson> CollegeDepartmentsActiveLessons { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new LessonConfiguration());
            modelBuilder.ApplyConfiguration(new StudentConfiguration());
            modelBuilder.ApplyConfiguration(new LecturerConfiguration());
            modelBuilder.ApplyConfiguration(new LessonOfStudentConfiguration());
            modelBuilder.ApplyConfiguration(new ActiveLessonConfiguration());
            modelBuilder.ApplyConfiguration(new CollegeDepartmentConfiguration());
            modelBuilder.ApplyConfiguration(new CollegeDepartmentsActiveLessonConfiguration());

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Todo Configuration read
            optionsBuilder.UseSqlServer("Data Source=DESKTOP-H2SJGIR;Initial Catalog=DbSchoolManagement;Integrated Security=True");
        }
    }
}

UnitOfWork.cs

namespace SchoolManagementApp.Dal.UnitOfWorks
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly AppDbContext _context;
        public UnitOfWork(AppDbContext context)
        {
            _context = context;
        }
        public void Commit()
        {
            _context.SaveChanges();
        }

        public async Task CommitAsync()
        {
            await _context.SaveChangesAsync();
        }
    }
}

IUnitOfWork.cs

namespace SchoolManagementApp.Core.UnitOfWorks
{
    public interface IUnitOfWork
    {
        Task CommitAsync();
        void Commit();
    }
}

IStudentRepository

namespace SchoolManagementApp.Core.Repositories
{
    public interface IStudentRepository : IGenericRepository<Student>
    {
    }
}

StudentRepository

namespace SchoolManagementApp.Dal.Repositories
{
    public class StudentRepository : GenericRepository<Student>,IStudentRepository
    {
        public StudentRepository(AppDbContext context) : base(context)
        {
        }
    }
}

Service.cs

namespace SchoolManagementApp.Service.Services
{
    public class Service<T> : IService<T> where T : class
    {
        private readonly IGenericRepository<T> _repository;
        private readonly IUnitOfWork _unitOfWork;
        public Service(IGenericRepository<T> genericRepository, IUnitOfWork unitOfWork)
        {
            _repository = genericRepository;
            _unitOfWork = unitOfWork;
        }
        //Service methods

IStudentService

namespace SchoolManagementApp.Core.Services
{
    public interface IStudentService : IService<Student> { }
}

StudentService

namespace SchoolManagementApp.Service.Services
{
    public class StudentService : Service<Student>, IStudentService
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IUnitOfWork _unitOfWork;
        public StudentService(IGenericRepository<Student> genericRepository, IUnitOfWork unitOfWork, IStudentRepository studentRepository) : base(genericRepository, unitOfWork)
        {
            _studentRepository = studentRepository;
            _unitOfWork = unitOfWork;
        }
    }
}

I tried to read some other stackoverflow threads but that didnt help me to resolve my problem.

>Solution :

The error is pretty clear:

Unable to resolve service for type ‘SchoolManagementApp.Dal.AppDbContext’ while attempting to activate ‘SchoolManagementApp.Dal.UnitOfWorks.UnitOfWork’

Your DbContext is not registered in the DI. Check out the DbContext Lifetime, Configuration, and Initialization article. Usually you setup you have in OnConfiguring on the injection level and provide ctor accepting DbContextOptions<AppDbContext>. Something along these lines:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    // not needed
    // protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {}
}

And registration:

builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseSqlServer("Data Source=DESKTOP-H2SJGIR;Initial Catalog=DbSchoolManagement;Integrated Security=True")); // better would be reading from config

Also check out Dependency injection in ASP.NET Core article.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading