Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I work with Ninject in an ASP.NET MVC Web App?

I've created a new MVC Web application and I have references to Ninject.dll, Ninject.Web.Common.dll and Ninject.Web.MVC.dll.

Global.asax.cs:

public class MvcApplication : NinjectHttpApplication     {         public static void RegisterGlobalFilters(GlobalFilterCollection filters)         {             filters.Add(new HandleErrorAttribute());         }          public static void RegisterRoutes(RouteCollection routes)         {             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");              routes.MapRoute(                 "Default", // Route name                 "{controller}/{action}/{id}", // URL with parameters                 new                 {                     controller = "Home",                     action = "Index",                     id = UrlParameter.Optional                 });         }          protected override IKernel CreateKernel()         {             var kernel = new StandardKernel();             kernel.Load(Assembly.GetExecutingAssembly());             return kernel;         }          protected override void OnApplicationStarted()         {             base.OnApplicationStarted();              AreaRegistration.RegisterAllAreas();             RegisterGlobalFilters(GlobalFilters.Filters);             RegisterRoutes(RouteTable.Routes);         }     } 

App_start\NinjectWebCommon:

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();             kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);             kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();              RegisterServices(kernel);             return kernel;         }          /// <summary>         /// Load your modules or register your services here!         /// </summary>         /// <param name="kernel">The kernel.</param>         private static void RegisterServices(IKernel kernel)         {         }             } 

I get the error "The sequence contains no elements". What am I doing wrong?

Error details:

Description: An unhandled exception occurred during the execution of the current web request. Examine the stack trace for more information about this error and where it originated in the code.  Exception Details: System.InvalidOperationException: Sequence contains no elements  Source Error:   Unhandled exception occurred during execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.   Stack Trace:  [InvalidOperationException: Последовательность не содержит элементов]    System.Linq.Enumerable.Single(IEnumerable`1 source) +320    Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectMvcHttpApplicationPlugin.cs:53    Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:52    Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:32    Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:52    Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:80 
like image 998
Mediator Avatar asked Apr 25 '12 07:04

Mediator


People also ask

How to use Ninject in Mvc?

To open Manage NuGet Package dialog just right click on MvcNInject and from List select Manage NuGet package. In search box enter Ninject MVC4. And select Ninject. MVC4 as show below and click on Install button and it will get installed.

What is ninject used for?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

Is ninject free?

Ninject is and will always be free for both personal and commercial projects. It's also open source, so you can fork the code and make any changes you like.


2 Answers

To be explicitly clear about this, if you use NuGet to add the 'Ninject.Mvc3' package (I used version 3.0.0.6), there is no need to make any modifications to global.asax.cs. The NuGet package does the magic for you by creating the NinjectWebCommon class in the App_Start folder of your MVC 4 project.

I say this because I seem to have followed a similar tutorial to the original poster (I followed an article on The Code Project called 'Dependency Injection in asp.net mvc4 and webapi using Ninject'), and had exactly the same issue as the original poster. The Code Project article doesn't make it clear that you should either use NuGet (and don't touch global.asax.cs or add the Ninject references manually (and amend global.asax.cs).

like image 139
Duncan Awerbuck Avatar answered Oct 17 '22 01:10

Duncan Awerbuck


You are deriving from NinjectHttpApplication AND you are using App_Start at the same time. Choose one! Read the docu of Ninject.MVC3 for more info.

like image 24
Remo Gloor Avatar answered Oct 16 '22 23:10

Remo Gloor