2
votes

I have getting error that "No parameterless constructor defined for this object." in MVC 5 Application.

Error

Controller is:

public class HomeController : Controller
    {
        private  IUserService userService;

        public HomeController(IUserService userService)
        {
            this.userService = userService;
        }

        [HttpGet]
        public ActionResult Index()
        {
            var user = userService.GetUser();
            return View();
        }
    }

Ninject WebCOmmon cs class is :

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(QuestionWave.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(QuestionWave.Web.App_Start.NinjectWebCommon), "Stop")]

namespace QuestionWave.Web.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using QuestionWave.Data;
    using QuestionWave.Service;

    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<QuestionWaveDbEntities>().ToSelf().InRequestScope();
            kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
            kernel.Bind<IUserService>().To<UserService>();
        }        
    }
}

I have installed four Packages for Ninject

    <package id="Ninject" version="3.2.2.0" targetFramework="net45" />
  <package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
  <package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net45" />
  <package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net45" /> 

My DbContext class is:

public partial class QuestionWaveDbEntities : DbContext
{
    public QuestionWaveDbEntities()
        : base("name=QuestionWaveDbEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<User> Users { get; set; }
}

I am using database first approach using EF. All constructors are public.

What going wrong with my code please suggest.

3
What does your UserService's constructor look like? - Jeroen Vannevel
@JeroenVannevel User Service constructor is: private readonly IRepository<User> userRepository; public UserService(IRepository<User> userRepository) { this.userRepository = userRepository; } - Sandeep Shekhawat
And what does Repository<User> its constructor look like? - Jeroen Vannevel
@JeroenVannevel It's generic repository : public class Repository<T> : IRepository<T> where T : class { private readonly QuestionWaveDbEntities context; public Repository(QuestionWaveDbEntities context) { this.context = context; } } - Sandeep Shekhawat

3 Answers

5
votes

I used this way and is working. Create Ninject dependency resolver class:

public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;
    public NinjectDependencyResolver()
    {
        kernel = new StandardKernel();
        AddBindings();
    }

    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }

    private void AddBindings()
    {
       kernel.Bind<IUserService>().To<UserService>();
    }
}

And set your dependency resolver in Global.asax Application_Start method,

DependencyResolver.SetResolver(new NinjectDependencyResolver());
0
votes

If you are using dropdownlist in View so you should change the attribute name from the list name which is being used to access the value.

example: @Html.DropDownListFor(m => Model.QualificationName, Model.QualificationList, "Select Qualification")

so these both name should be separated: "QualificationName, QualificationList"

0
votes

For me the problem was that I had circular dependencies in my project and Ninject could't resolve the dependencies. Once I deleted the circular dependencies my project started working again.