asp.net-mvc - 没有为此对象定义无参数构造函数。注入(inject) + MVC 5

标签 asp.net-mvc entity-framework dependency-injection ninject

我收到错误消息“没有为此对象定义无参数构造函数。”在 MVC 5 应用程序中。

Error

Controller 是:

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 类是:

[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>();
        }        
    }
}

我已经为 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" /> 

我的 DbContext 类是:

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; }
}

我使用的是使用 EF 的数据库优先方法。 所有构造函数都是公开的。

我的代码出了什么问题,请提出建议。

最佳答案

我用过这种方式并且正在工作。创建 Ninject 依赖解析器类:

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>();
    }
}

并在 Global.asax Application_Start 方法中设置依赖解析器,

DependencyResolver.SetResolver(new NinjectDependencyResolver());

关于asp.net-mvc - 没有为此对象定义无参数构造函数。注入(inject) + MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014067/

相关文章:

php - 在 PHP 中使用依赖注入(inject)组合 Controller 类

dependency-injection - 全局状态和单例依赖注入(inject)

asp.net - CheckBoxList 多选 : difficulty in model bind back

asp.net-mvc - 导航栏上的集中按钮

c# - 转发到 Controller 的动态 DateTime 控件数量

linq - Entity Framework 和 LINQ - 算术运算导致溢出

entity-framework - 如何在代码中指定 EF byte[] 首先超过 8000 字节?

.net - EF 6 - 一对多级联删除,无需反向引用

javascript - ASP Net MVC 从 JS 错误调用 Controller 中的函数

java - 除了构造函数 @Inject 注解之外,还有其他方式实现 GWTP placeManager