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

问题描述 投票:1回答:3

在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.com中,这是我所做的

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

但是当我运行应用程序时,我在浏览器上收到错误消息,提示未找到无参数构造函数。而且,如果我创建的参数少了构造函数,则不会实例化我的存储库。因此,无论我在存储库中调用该方法的何处,该值均为null。我怎么解决这个问题?还是让MVC或Ninject知道要调用哪个构造函数?

c# dependency-injection ninject asp.net-mvc-5
3个回答
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>();
        }
    }
}

2
投票

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

欢呼声


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

© www.soinside.com 2019 - 2024. All rights reserved.