Инъекция зависимостей Mvc 5 unity : что не так в моем коде?
Привет, я впервые использую инъекцию зависимостей и единицу работы в образцовом проекте.
IUnitOfWork.в CS
using System; using WDCS.BusinessLogic.Infrastructure.Interfaces.UserRepo; namespace WDCS.BusinessLogic.Infrastructure.Interfaces { public interface IUnitOfWork : IDisposable { IUserRepository UesrRepository { get; } void SaveChages(); } }
UnitOfWork.в CS
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
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
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()); } } }
но когда я запускаю приложение и пытаюсь ударить http://localhost/WDCS/api/Login/ping[^] получение следующей ошибки.
{"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)"}}
Пожалуйста, помогите мне решить эту проблему.
Что я уже пробовал:
Я попробовал все, что у меня есть на этих ссылках
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
Я последовал тому же самому, но не смог понять, в чем именно заключается проблема.