简体   繁体   English

C#MVC控制器在登录时中断

[英]C# MVC controller breaks on Login

InvalidOperationException: Unable to resolve service for type 'Echelon.Data.IAssignmentRepository' while attempting to activate 'Echelon.Controllers.SessionController'. InvalidOperationException:尝试激活“ Echelon.Controllers.SessionController”时无法解析“ Echelon.Data.IAssignmentRepository”类型的服务。

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 如果使用的是asp.net核心使用的默认依赖项注入框架,则应在Startup.cs类的ConfigureServices方法中注册它。

services.AddTransient<IAssignmentRepository , AssignmentRepository>();

where AssignmentRepository is a your concrete class where you are implementing the IAssignmentRepository interface. 其中AssignmentRepository是您要实现IAssignmentRepository接口的具体类。

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. 在这里,我只是硬编码了Assignments属性以返回2个CreateAssignment对象。 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 现在,当对控制器操作方法提出新请求时,框架将创建一个新的SessionController对象,并将一个AssignmentRepository对象传递给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. 如果您不熟悉依赖项注入的概念,强烈建议您花16分钟的时间阅读docs.microsoft.com上的出色文档,然后再尝试编写任何其他代码。

Introduction to Dependency Injection in ASP.NET Core ASP.NET Core中的依赖注入简介

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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