Ninject.MVC3. Bootstrapper.Initialize throws "Sequence contains no elements"
Asked Answered
I

4

8

this question is not new, but my problem seems to have a different root than those I have seen so far.

I have a solution containing several projects: two of them are C# MVC4. I installed Ninject.MVC3 Nuget package on both and I am using the NinjectWebCommon class in App_Start folder approach (https://github.com/ninject/Ninject.Web.Mvc/wiki/Setting-up-an-MVC3-application).

Versions:

  1. Ninject 3.2.2.0
  2. Ninject.MVC3 3.2.1.0
  3. Ninject.Web.Common 3.2.3.0
  4. Ninject.Web.Common.WebHost 3.2.3.0
  5. WebActivator 2.0.5

NinjectWebCommon.cs of the first project:

using System.Web.Mvc;
using Ninject.Web.Mvc.FilterBindingSyntax;
using S1.MVC.Filters.CentralAutenticacao.Business;
using S1.MVC.Filters.Error;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(S1.CRM.Eventos.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(S1.CRM.Eventos.App_Start.NinjectWebCommon), "Stop")]

namespace S1.CRM.Eventos.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    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)
        {
            kernel.BindFilter<FiltroCentralAutenticacao>(FilterScope.Global, 0);
            kernel.BindFilter<GenericErro>(FilterScope.Global, 0);
        }        
    }
}

NinjectWebCommon.cs of the second project:

using System.Web.Mvc;
using Ninject.Web.Mvc.FilterBindingSyntax;
using S1.MVC.Filters.CentralAutenticacao.Business;
using S1.MVC.Filters.Error;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(S1.CRM.Crud.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(S1.CRM.Crud.App_Start.NinjectWebCommon), "Stop")]

namespace S1.CRM.Crud.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    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)
        {
            kernel.BindFilter<FiltroCentralAutenticacao>(FilterScope.Global, 0);
            kernel.BindFilter<GenericErro>(FilterScope.Global, 0);
        }        
    }
}

Here is the global.asax file of the first project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace S1.CRM.Eventos
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

and of the second one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace S1.CRM.Crud
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

When I try to run any of the two projects, I get an InvalidOperationException saying "Sequence contains no elements" when calling

bootstrapper.Initialize(CreateKernel);

Stacktrace:

in System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
in Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start()
in Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c)
in Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
in Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback)
in S1.CRM.Eventos.App_Start.NinjectWebCommon.Start() in d:\git-paulo\S1.CRM\S1.CRM.Eventos\App_Start\NinjectWebCommon.cs:line 30

Some people had this problem when they make global.asax derive from NinjectHttpApplication and also use NinjectWebCommon class, or when they rename assemblies (Ninject + MVC3 = InvalidOperationException: Sequence contains no elements). That's not my case.

Other guy got this error when two projects in the same solution where using WebActivator to initialize Ninject (Ninject for Web Site and Api - Sequence contains no elements). So I tried to unload one of the projects, but still kept getting the error.

Any ideas on what is going on?

Iorgo answered 29/10, 2014 at 13:50 Comment(2)
Can you also post which exact method inside Ninject throws this exception (you might also have to check the innerexceptions as well)?Goforth
I added the stacktrace of the exception. There is no inner exception. ThanksIorgo
I
9

Indeed there was another project using WebActivator in the solution: a class library referenced by one of the MVC projects. I didn't suspect of it, because it doesn't make any sense to have WebActivator in there.

Iorgo answered 29/10, 2014 at 16:48 Comment(0)
M
2

This error also occurs if there is are Exists 2 code files references +NinjectWebCommon.cs (located usually in App_Start folder) in the solution.

If there are multiple Initialize() method exist this also results error similar to “Sequence contains no elements

Minnesinger answered 30/6, 2017 at 20:6 Comment(0)
M
0

I have experienced the “Sequence contains no elements” due to my references. Please check your references. If there is a reference to another project which contains Ninject Infrastructure directory also causes the error. If you delete it problem may be solved.

Malley answered 12/4, 2017 at 7:24 Comment(0)
W
0

This also happened to me for a different reason - I had two Bootstrapper instances each trying to initialise a Ninject kernel.

That is to say, I had the typical NinjectWebCommon code in two places because when I updated Ninject (with nuget), the update process inserted a new code file in the default place. Originally I had moved the typical NinjectWebCommon code elsewhere.

Wegner answered 31/5, 2018 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.