简体   繁体   中英

C# MVC controller breaks on Login

InvalidOperationException: Unable to resolve service for type 'Echelon.Data.IAssignmentRepository' while attempting to activate 'Echelon.Controllers.SessionController'.

I keep getting this Error whenever I try to login or click something in my navbar, I'm confused as to why it's erroring out, can someone please help? This started when I got email verification working, then whenever I try to login or click anything I get the error?

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Echelon.Models.SessionViewModels;
using Echelon.Classes;
using Microsoft.AspNetCore.Identity;
using Echelon.Models;
using Echelon.Data;

namespace Echelon.Controllers
{
    public class SessionController : Controller
    {
        StoredProcedure storedProcedure = new StoredProcedure();

        private IAssignmentRepository repository;
        private readonly AssignmentDbContext _context;

        public SessionController(IAssignmentRepository repo, AssignmentDbContext context)
        {
            repository = repo;
            _context = context;
        }

        [Authorize]
        public IActionResult Home()
        {
            return View();
        }

        public IActionResult Courses()
        {
            var Courses = storedProcedure.getCourseNames(User.Identity.Name);
            var CoursesView = new CoursesViewModel();

            foreach (var Course in Courses.ToList())
            {
                Course course = new Course();
                course.CourseName = Course;
                CoursesView.Courses.Add(course);
            }

            return View(CoursesView);
        }

        public IActionResult CreateCourse()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CreateCourse(CreateCourseModel course)
        {
            if (ModelState.IsValid)
            {
                storedProcedure.addCourse(User.Identity.Name, course.CourseName, course.CourseDesc, course.StartDate, course.EndDate);
                return RedirectToAction("Courses");
            }
            else
            {
                return View();
            }
        }

        public IActionResult Assignments(string courseName)
        {
            var assignments = storedProcedure.getAssignments(User.Identity.Name, courseName);
            var AssignmentsView = new AssignmentsViewModel { CourseName = courseName };

            foreach (var Assignment in assignments.ToList())
            {
                AssignmentsView.Assignments.Add(Assignment);
            }
            return View(AssignmentsView);
        }

        public IActionResult CreateAssignment(string courseName)
        {
            CreateAssignment assignmentModel = new CreateAssignment();
            assignmentModel.CourseName = courseName;
            assignmentModel.UserName = User.Identity.Name;
            return View(assignmentModel);
        }

        [HttpPost]
        public async Task<IActionResult> CreateAssignment([Bind("AssignmentID,UserName,CourseName,AssignmentName,AssignmentDescription,TotalPoints,DueDate")] CreateAssignment assignment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(assignment);
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    return View(assignment);
                }
                //return View(assignment);
                return RedirectToAction("Assignments", "Session", new { courseName = assignment.CourseName });
            }
            else
                return View(assignment);
        }

        public IActionResult Students(string courseName)
        {
            var students = storedProcedure.getStudents(User.Identity.Name, courseName);
            var studentsView = new StudentsViewModel();

            foreach (var student in students.ToList())
            {
                Student Student = new Student();
                Student.StudentFName = student.StudentFName;
                Student.StudentLName = student.StudentLName;
                Student.CourseName = student.CourseName;
                studentsView.Students.Add(Student);
            }
            return View(studentsView);
        }

        public IActionResult AllStudents()
        {
            var students = storedProcedure.getAllStudents(User.Identity.Name);
            var studentsView = new AllStudentsViewModel();

            foreach (var student in students.ToList())
                studentsView.Students.Add(student);
            return View(studentsView);
        }

        public IActionResult Attendance()
        {
            return View();
        }
    }
}

You usually get that error when you are trying to use an implementation of an interface, but you have not registered the concrete implementation you want to use with the framework.

If you are using the default dependency injection framework used by asp.net core, you should register it in the ConfigureServices method in Startup.cs class

services.AddTransient<IAssignmentRepository , AssignmentRepository>();

where AssignmentRepository is a your concrete class where you are implementing the IAssignmentRepository interface.

public interface IAssignmentRepository
{
    IEnumerable<CreateAssignment> Assignments { get; }
}

public class AssignmentRepository : IAssignmentRepository
{
    public IEnumerable<CreateAssignment> Assignments
    {
        get
        {
            return new List<CreateAssignment>()
            {
                new CreateAssignment(),
                new CreateAssignment()
            };
        }
    }
}

Here i just hard coded the Assignments property to return 2 CreateAssignment objects. But i guess you probably will be reading it from database and return it.

Now when a new request comes for your controller action method, the framework will create a new object of SessionController and pass an object of AssignmentRepository to the constructor of SessionController

If you are not familiar with the dependency injection concept, i strongly suggest you to spend 16 minutes to read the excellent documentation on docs.microsoft.com before trying to write any further code.

Introduction to Dependency Injection in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM