3

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]'.)'

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.

2
  • 6
    builder.Services does not register the AppDbContext. That's why it fails to initialize anything which is dependent on AppDbContext. Commented Apr 28, 2023 at 14:13
  • 4
    I don't see a call to register DbContext - learn.microsoft.com/en-us/dotnet/api/… Commented Apr 28, 2023 at 14:15

1 Answer 1

2

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 the setup you have in the OnConfiguring is done via the injection 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.