MVC5和Ninject:无参数构造函数错误

时间:2014-01-23 15:28:51

标签: c# dependency-injection ninject asp.net-mvc-5

在MVC 5中,我们得到了这样的帐户控制器。

public class AccountController : Controller
        {

            public AccountController()
                : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DatePickerDbContext())))
            {

            }

            public AccountController(UserManager<ApplicationUser> userManager)
            {
                UserManager = userManager;
            }
        }

我安装了Ninject来处理我的依赖注入。我有两个存储库,我想在我的AccountController中使用 现在代码看起来像这样

    public class AccountController : Controller
    {
              private readonly ILicenserepository _licenserepository;
              private readonly IUserRepository _userRepository;    

        public AccountController(ILicenserepository licenserepository, IUserRepository userRepository)
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DatePickerDbContext())))
        {
            _licenserepository = licenserepository;
            _userRepository = userRepository;
        }

        public AccountController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }
    }

在ninject.web.common中这就是我所做的

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind(typeof (ILicenserepository)).To(typeof (Licenserepository));
    kernel.Bind(typeof (IUserRepository)).To(typeof (UserRepository));
}    

但是当我运行应用程序时,我在浏览器上收到错误,指出没有找到参数化的构造函数。如果我创建参数较少的构造函数,我的存储库不会被实例化。因此,无论我从存储库调用该方法,值都为null。 我怎么解决这个问题?或者让MVC或Ninject知道要调用哪个构造函数?

3 个答案:

答案 0 :(得分:6)

您需要在Global.asax.cs

中注册DependencyResolver

注册看起来像这样:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterDependencyResolver();
}

private void RegisterDependencyResolver()
{
    var kernel = new StandardKernel();

    // you may need to configure your container here?
    RegisterServices(kernel);

    DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}

DependencyResolver

public class NinjectDependencyResolver : IDependencyResolver
{
    private readonly IKernel kernel;

    public NinjectDependencyResolver(IKernel kernel)
    {
        this.kernel = kernel;
    }

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

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return this.kernel.GetAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }
}

答案 1 :(得分:2)

这是一个更新: 如果您正在使用MVC5和WebAPI 2,那么您需要做的就是使用NuGet Manager并将NinjectMVC5和NinjectWebApi2添加到您的项目中。然后错误就消失了。 (使用Visual Studio 2013)

干杯

答案 2 :(得分:0)

使用.NET MVC 5和Ninject 3.3.4,我可以正常工作。

已采取的步骤:

  1. 安装Ninject 3.3.4
  2. 安装Ninject.Web.Common 3.3.1
  3. 安装Ninject.Web.Common.WebHost 3.3.1
  4. 安装Ninject.MVC5 3.3.0(用于MVC Controller

(可选)Api控制器步骤

  1. 安装Ninject.Web.WebApi 3.3.0(与api ApiController结合使用)
  2. 安装Ninject.Web.WebApi.WebHost(与ApiController一起使用)

这里的重要区别是您的项目使用的是Api控制器还是Mvc控制器。如果您不熟悉这些区别,请查看以下帖子:

Difference between ApiController and Controller in ASP.NET MVC

注意: 我没有不必对Ninject.Web.Common.cs文件进行任何其他配置。下面是我的配置,省略了绑定


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

namespace YourProject.Web.App_Start
{
    using System;
    using System.Web;
    using Microsoft.Web.Infrastructure.DynamicModuleHelper;
    using Ninject;
    using Ninject.Web.Common;
    using Ninject.Web.Common.WebHost;

    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)
        {
            // Common

            // Repositories

            // Services

            // Factories

            // Misc
        }        
    }
}