Использование ninject с Ninject.Web.Api для Web Api 2 не работает в ASP.NET MVC 5

Я разрабатываю проект Asp.NET MVC. В моем проекте также есть веб-API. Я использую ASP.NET MVC5 и Web Api 2 с Visual Studio 3. Я выполняю внедрение зависимостей с помощью ninject. Я знаю, что Ninject для Интернета не работает для Web Api 2. Поэтому я попытался использовать Ninject для Web Api.

Я установил пакет ninject для веб-api 2 с помощью диспетчера пакетов nuget

введите здесь описание изображения

Затем я установил Ninject.Web с помощью диспетчера пакетов nuget.

введите здесь описание изображения

Затем в NinjectWebCommon я добавил эту строку в RegisterServices

private static void RegisterServices(IKernel kernel)
        {
            System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
            kernel.Bind<ICategoryRepo>().To<CategoryRepo>();
        }    

Это мой полный класс NinjectWebCommon, регистрирующий одну зависимость

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

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

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using PatheinFashionStore.Domain.Abstract;
    using PatheinFashionStore.Domain.Concrete;

    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>();
                System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
                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<ICategoryRepo>().To<CategoryRepo>();
        }        
    }
}

Это мой контроллер

 public class HomeController : Controller
    {
        private ICategoryRepo categoryRepo;

        public HomeController(ICategoryRepo categoryRepoParam)
        {
            this.categoryRepo = categoryRepoParam;
        }

        public ActionResult Index()
        {
            return View();
        }
}

Затем, когда я запускаю свой код, он выдает мне эту ошибку

введите здесь описание изображения

Обновлять

Но когда я получаю доступ к apiController, он работает.

Вот мой веб-контроллер api

 public class TestController : ApiController
    {
        private ICategoryRepo categoryRepo;

        public TestController(ICategoryRepo categoryRepoParam)
        {
            this.categoryRepo = categoryRepoParam;
        }

        public string Get()
        {
            this.categoryRepo.Create();
            return "OK";
        }
    }

Итак, я обнаружил, что он работает для веб-API, но не работает для веб-проекта. Я использую оба в одном проекте.


person Wai Yan Hein    schedule 19.06.2016    source источник
comment
Установите Ninject.MVC5 через Nuget, если вы хотите использовать стандартный контроллер MVC.   -  person James P    schedule 19.06.2016


Ответы (1)


Вам необходимо установить Ninject.MVC5 и настроить DependencyResolver для MVC вместе с DependencyResolver для WebApi

// Web Api
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

// MVC 
System.Web.Mvc.DependencyResolver.SetResolver(new Ninject.Web.Mvc.NinjectDependencyResolver(kernel));
person jbl    schedule 20.06.2016
comment
Спасибо. Оно работает. Но я добавил только эту строку System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver (kernel); в методе создания ядра. Это работает для обоих. Так почему? Вторая строка не нужна? Очень хотелось бы узнать об этом подробнее. Не могли бы вы объяснить об этом? - person Wai Yan Hein; 20.06.2016