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

2019-03-22 17:11发布

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

3条回答
叼着烟拽天下
2楼-- · 2019-03-22 17:33

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-03-22 17:54

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

查看更多
聊天终结者
4楼-- · 2019-03-22 17:57

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.

查看更多
登录 后发表回答