0

I am trying to implement dependency injection in the ASP.NET (MVC) template program.

Program Structure:

enter image description here

I have the following class/interfaces in the Model folder:

Employee.cs

namespace TestWebApplication.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string FullName { get; set; }
    }
}

IEmployeeRepository.cs

namespace TestWebApplication.Models
{
    public interface IEmployeeRepository
    {
        Employee GetEmployee(int employeeId);
    }
}

EmployeeRepository.cs

namespace TestWebApplication.Models
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private List<Employee> _employeeList;

        public EmployeeRepository()
        {
            _employeeList = new List<Employee>()
            {
                new Employee() {EmployeeID = 1, FullName = "ABC"},
                new Employee() {EmployeeID = 2, FullName = "XYZ"},
            };
        }
        public Employee GetEmployee(int employeeId)
        {
            return _employeeList.First();
        }
    }
}

and now, when I try to do the dependency injection in the HomeController and run the web application, it throws exception.

HomeController .cs

namespace TestWebApplication.Controllers
{
    public class HomeController : Controller
    {
        IEmployeeRepository _employeeList;
        public HomeController(IEmployeeRepository repo)
        {
            _employeeList = repo;
        }
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

         public ActionResult Basics()
        {
            ViewBag.Message = "Your Basics page.";

            return View();
        }
    }
}

Exception:

No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean & canBeCached, RuntimeMethodHandleInternal & ctor, Boolean & bNeedSecurityCheck) + 0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark & stackMark) + 122
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark & stackMark) + 239
   System.Activator.CreateInstance(Type type, Boolean nonPublic) + 85
   System.Activator.CreateInstance(Type type) + 12
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) + 55

[InvalidOperationException: An error occurred when trying to create a controller of type 'TestWebApplication.Controllers.HomeController'.Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) + 178
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) + 80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) + 102
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController & controller, IControllerFactory & factory) + 188
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) + 50
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) + 48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) + 16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() + 105
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) + 50
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean & completedSynchronously) + 163

QUESTION: How do I register the EmployeeRepository?

skm
  • 5,015
  • 8
  • 43
  • 104
  • What dependency injection container are you using? From the error message and stack trace, I'd say you're not currently using one. – ProgrammingLlama Apr 22 '22 at 09:37
  • @DiplomacyNotWar: Sorry, I am absolutely new to Web Development and have no idea about DI Container (searching about it now). – skm Apr 22 '22 at 09:40
  • I'm not saying you should use this one (there are many available), but you can look at how Autofac works with ASP.NET here: https://autofac.readthedocs.io/en/latest/integration/mvc.html#id2 – ProgrammingLlama Apr 22 '22 at 09:41
  • If you're starting a new project, it might be better if you do it using ASP.NET Core instead, since that has dependency injection out of the box. – ProgrammingLlama Apr 22 '22 at 09:41
  • There are many DI Containers to choose from. Here's the MVC integration page for [Simple Injector](https://docs.simpleinjector.org/en/latest/mvcintegration.html), [Ninject](https://github.com/ninject/ninject.web.mvc), [LightInject](https://www.lightinject.net/mvc/), [Autofac](https://autofac.readthedocs.io/en/latest/integration/mvc.html#id2). – Steven Apr 22 '22 at 09:53
  • @DiplomacyNotWar: Thanks, I will go with using ASP.NET Core instead and use the `ConfigureServices()` for registration. – skm Apr 22 '22 at 09:55
  • You can also implement DI without DI Container (a.k.a. [Pure DI](https://blog.ploeh.dk/2014/06/10/pure-di/)). This can be done by implementing a custom `IControllerFactory` (by inheriting from `DefaultControllerFactory` and creating your controllers from within the `GetControllerInstance` method). You can replace the default controller factory by calling `ControllerBuilder.Current.SetControllerFactory([my controller factory)` at startup. – Steven Apr 22 '22 at 10:04
  • Related: https://stackoverflow.com/questions/12605445/mvc-no-parameterless-constructor-defined-for-this-object. Note that there are many, many questions on Stack Overflow about the MVC "No parameterless constructor defined for this object." error. – Steven Apr 22 '22 at 10:05
  • btw, If you're starting a new web site, you might instead consider building it with ASP.NET Core MVC, instead of the -now legacy- ASP.NET MVC. – Steven Apr 22 '22 at 10:16
  • @Steven Thanks for the suggestions. I will go with creating the website using ASP.NET Core MVC. – skm Apr 22 '22 at 10:30

0 Answers0