26

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
Duncan Awerbuck
  • 503
  • 4
  • 7
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • Can you add the full stacktrace? – Remo Gloor Apr 25 '12 at 10:12
  • [Line 53](https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/Ninject.Web.Mvc/NinjectMvcHttpApplicationPlugin.cs#L53) appears to be trying to remove the [DataAnnotationsModelValidatorProvider](http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelvalidatorprovider.aspx) from MVC. Are you using the right version of MVC / have you configured it yourself in some way? – Rup Apr 25 '12 at 10:38

3 Answers3

40

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).

Duncan Awerbuck
  • 503
  • 4
  • 7
24

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.

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • Ah, neat - so the reason he's seeing the error about removing DataAnnotationsModelValidatorProvider is that he's initialising Ninject the second time and the first init already removed it? I guess that's a useful catch but it should probably fail more gracefully – Rup Apr 25 '12 at 13:55
  • 5
    @Remo Gloor - I have to say these two different approaches are incredibly confusing for the beginner even with the documentation. The documentation does indeed essentially say 'they are exactly the same' but looking at the code the Nuget way has an empty 'RegisterServices' method and the NinjectHttpApplication way has 'kernal.Load(Assembly.GetExecutingAssemby)'. These aren't the same and more guidance on that page of documentation would be very much appreciated. This is one of the first pages people are likely to find on Ninject and a little more detail would be great for beginneres – Simon_Weaver Dec 14 '12 at 08:45
  • @Simon_Weaver Added RegisterServices method to the NinjectHttpApplication way to have the same implementation of the registration code. Now it is really the same. If you need more information them add TODO's what is missing in your opinion or add it yourself if you know the answer. – Remo Gloor Dec 17 '12 at 07:59
  • 2
    I'd like to see an example of accessing the kernel created via the NinjectWebCommon class. I have a custom controller factory and am having issues trying to work out where I can access this instance of the kernel from. – Stephen Price Apr 10 '16 at 15:05
7

Be sure you are not referencing a project which also uses the NinjectMVC3 App_Start. After removing the reference to such, my project started working. Also, as said before, check the namespaces all match and are correct.

dwbrito
  • 5,194
  • 5
  • 32
  • 48