Я разрабатываю проект 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, но не работает для веб-проекта. Я использую оба в одном проекте.
Ninject.MVC5
через Nuget, если вы хотите использовать стандартный контроллер MVC. - person James P   schedule 19.06.2016