Click here to Skip to main content
15,894,740 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
Posted
Updated 9-Jan-20 4:59am
v2

You no need to change anything in your code but just use install-package Unity.WebApi instead. Hope it helps!
 
Share this answer
 
Comments
Richard Deeming 3-Aug-17 10:47am    
This question was asked, answered, and solved over a year ago.
Barsan Baris 11-Oct-19 3:58am    
thanks it worked for me.
Sandro Pegoraro 19-Jun-20 18:02pm    
thou sir have saved my life, f
After doing lot of search got the solution. Above is also right but this for simple MVC and I needed for MVC WebAPI. here is link for solution
Dependency Injection in ASP.NET Web API 2 | The ASP.NET Site[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



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