none
MVC Dependency Injection issue with model class in creating index view

    Pertanyaan

  • hi

    I am implementing dependency injection for my MVC application using UnityConfig. I used entity framework and added tables to my Class Library repository that I referenced. When I am trying to build my views from the controller. I couldn't find the model name that I used in the class library but I am able to consume tables in the controller.

    Please help me out where I would have done mistakes.

    Thank you in Advance!!

    Siddhartha



    • Diedit oleh Siddhartha K Jumat, 25 Mei 2018 03.21
    • Dipindahkan oleh CoolDadTxMVP Jumat, 25 Mei 2018 14.13 ASP.NET related
    Jumat, 25 Mei 2018 03.18

Semua Balasan

  • When I am trying to build my views from the controller. I couldn't find the model name that I used in the class library but I am able to consume tables in the controller.

    I'll help you out a little bit here. However, ASP.NET MVC should be addressed at the ASP.NET forums.

    https://forums.asp.net/

    It shouldn't be happening in the controller. You should learn how to implement SoC, which you are kind of doing with the repository pattern with the repository being addressed in the model and not the controller.

    https://en.wikipedia.org/wiki/Separation_of_concerns

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/overview/understanding-models-views-and-controllers-cs

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

    <end>

    You see an example of SoC where Unity IoC is being used. But further discussion should be addressed at the ASP.NET forums and not the C# forum. 

    using System.Data;
    using System.Data.Common;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.Owin.Security;
    using Microsoft.Practices.Unity;
    using Unity.Mvc5;
    using ServiceLayer;
    using WebAPI.Controllers;
    using MVC.Models;
    
    
    namespace MVC.App_Start
    {
        public static class IocExtensions
        {
            public static void BindInRequestScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new HierarchicalLifetimeManager());
            }
    
            public static void BindInSingletonScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new ContainerControlledLifetimeManager());
            }
        }
    
        public class UnityMVC5
        {
            public static void Start()
            {
                var container = BuildUnityContainer();
                DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            }
    
            private static IUnityContainer BuildUnityContainer()
            {
                var container = new UnityContainer();
    
                //Models
                container.BindInRequestScope<IStudentModels, StudentModels>();
                container.BindInRequestScope<IEnrollmentModels, EnrollmentModels>();
    
                //SeviceLayer
                container.BindInRequestScope<IServiceA, ServiceA>();
    
                //WebAPI controllers
                container.BindInRequestScope<IStudentControllerAPI, StudentController>();
                container.BindInRequestScope<IEnrollmentControllerAPI, EnrollmentController>();
    
                //asp.net idenity
    
                container.RegisterType<ApplicationDbContext>();
                container.RegisterType<ApplicationSignInManager>();
                container.RegisterType<ApplicationUserManager>();
                container.RegisterType<IAuthenticationManager>(
                                 new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
                container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                            new InjectionConstructor(typeof(ApplicationDbContext)));
    
                return container;
            }
        }
    }
    
    -------------------------------------------------------
    
    using System.Web.Mvc;
    using MVC.Models;
    
    namespace MVC.Controllers
    {
        [Authorize]
        public class StudentsController : BaseController  
        {
            private IStudentModels studmods;
            public StudentsController(IStudentModels studentModels)
            {
                studmods = studentModels;
            }
    
            // GET: Students
    
            [AllowAnonymous]
            public ActionResult Index()
            {
                return View(studmods.GetStudents());
            }
    
            //[AllowAnonymous]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(studmods.GetStudentById(id));
            }
            public ActionResult Create()
            {
                return View(studmods.Create());
            }
    
            [HttpPost]
            public ActionResult Create(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Create(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
    
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(studmods.Edit(id));
            }
    
            [HttpPost]
            public ActionResult Edit(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Edit(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
            public ActionResult Delete(int id = 0 )
            {
                if (id > 0) studmods.Delete(id);
                
                return RedirectToAction("Index");
             }
        }
    }
    
    ---------------------------------------------------------
    
    using System.Collections.Generic;
    using Entities;
    using WebAPI.Controllers;
    
    namespace MVC.Models
    {
        public class StudentModels : IStudentModels
        {
            private IStudentControllerAPI studapi;
            public StudentModels(IStudentControllerAPI studentControllerApi)
            {
                studapi = studentControllerApi;
            }
    
            public StudentViewModels GetStudents()
            {
                var dtos = studapi.GetStudents();
               
                var vm = new StudentViewModels {Students = new List<StudentViewModels.Student>()};
    
                foreach (var dto in dtos)
                {
                    var student = new StudentViewModels.Student
                    {
                        StudentID = dto.StudentID,
                        LastName = dto.LastName,
                        FirstName = dto.FirstName,
                        EnrollmentDate = dto.EnrollmentDate
                    };
    
                    vm.Students.Add(student);
                }
    
                return vm;
            }
    
            public StudentViewModels.Student GetStudentById(int id)
            {
                var dto = studapi.GetStudentById(id);
    
                var student = new StudentViewModels.Student
                {
                    StudentID = dto.StudentID,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName,
                    EnrollmentDate = dto.EnrollmentDate,
                    EnrollsandCourses = new List<EnrollandCourseViewModel.EnrollandCourse>()
                };
    
                foreach (var dtoec in dto.EnrollsandCourses)
                {
                    var ec = new EnrollandCourseViewModel.EnrollandCourse
                    {
                        Credits = dtoec.Credits,
                        Grade = dtoec.Grade,
                        Title = dtoec.Title
                    };
    
                    student.EnrollsandCourses.Add(ec);
                }
    
                return student;
            }
    
            public StudentViewModels.Student Create()
            {
                var student = new StudentViewModels.Student();
    
                return student;
            }
    
            public void Create(StudentViewModels.Student student)
            {
                var dto = new DTOStudent
                {
                    StudentID = student.StudentID,
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    EnrollmentDate = student.EnrollmentDate
                };
    
                studapi.CreateStudent(dto);
            }
    
            public StudentViewModels.Student Edit(int id)
            {
                var dto = studapi.GetStudentById(id);
    
                var student = new StudentViewModels.Student
                {
                    StudentID = dto.StudentID,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName,
                    EnrollmentDate = dto.EnrollmentDate
                };
    
                return student;
            }
    
            public void Edit(StudentViewModels.Student student)
            {
                var dto = new DTOStudent
                {
                    StudentID = student.StudentID,
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    EnrollmentDate = student.EnrollmentDate
                };
    
                studapi.UpdateStudent(dto);
            }
    
            public void Delete(int id)
            {
                studapi.DeleteStudent(id);
            }
        }
    }
    

    Jumat, 25 Mei 2018 10.33
  • Please post questions related to MVC in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Jumat, 25 Mei 2018 14.12