Click here to Skip to main content
15,895,538 members

Mvc 5 unity dependency injection : whats wrong in my code?

Vi(ky asked:

Open original thread
Hi I am first time using dependency injection and unit of work in sample project.

IUnitOfWork.cs
C#
using System;
using WDCS.BusinessLogic.Infrastructure.Interfaces.UserRepo;

namespace WDCS.BusinessLogic.Infrastructure.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        IUserRepository UesrRepository { get; }
        void SaveChages();
    }
}

UnitOfWork.cs

C#
using System;
using WDCS.BusinessLogic.Infrastructure.Interfaces;
using WDCS.BusinessLogic.Infrastructure.Interfaces.UserRepo;
using WDCS.Data;
using WDCS.SqlRepository.UserRepo;

namespace WDCS.SqlRepository
{
    public class UnitOfWork : IUnitOfWork
    {
        public WDCSContext db = null;
        public UnitOfWork()
        {
            db = new WDCSContext();
        }

        public IUserRepository _uesrRepository;

        public IUserRepository UesrRepository
        {
            get
            {
                if (_uesrRepository == null)
                {
                    _uesrRepository = new UserRepository(db);
                }
                return _uesrRepository;
            }
        }
            

        public void SaveChages()
        {
            db.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    db.Dispose();
                }
            }
            this.disposed = true;
        }


        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

UnityConfig.cs
C#
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc5;

using WDCS.BusinessLogic.Infrastructure.Interfaces;
using WDCS.SqlRepository;

namespace WDCS.WebApi
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
			var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterType<IUnitOfWork, UnitOfWork>();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}

LoginController.cs
C#
using WDCS.BusinessLogic.Infrastructure.Interfaces;
using WDCS.Data;

namespace WDCS.WebApi.Controllers
{
    public class LoginController : ApiController
    {

        private IUnitOfWork _uow = null;
        public LoginController(IUnitOfWork uow)
        {
            _uow = uow;
        }

        [HttpPost]
        public IHttpActionResult Login([FromBody] User user)
        {
            var res = _uow.UesrRepository.Login(user.userName, user.password);
            if (res != null)
                return Ok(res);
            else
                return BadRequest("Invalid Username or password");
        }

        [HttpGet]
        public IHttpActionResult Ping()
        {
            return Ok(_uow.UesrRepository.GetAll());
        }
    }
}


but when I am running the app and trying to hit http://localhost/WDCS/api/Login/ping[^] getting following error.
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'LoginController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Type 'WDCS.WebApi.Controllers.LoginController' does not have a default constructor","ExceptionType":"System.ArgumentException","StackTrace":"   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}


Please help me to solve this issue.

What I have tried:

I have tried whatever I got on these links

http://sarangasl.blogspot.in/2015/04/mvc-5-with-unity-for-dependency.html
http://www.dotnet-tricks.com/Tutorial/dependencyinjection/632V140413-Dependency-Injection-in-ASP.NET-MVC-4-using-Unity-IoC-Container.html

I followed the same but not able to figure out what is the exact issue.
Tags: C#, ASP.NET, MVC5

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900