如何在ASP.NET MVC Web App中使用Ninject?

时间:2012-04-25 07:45:32

标签: c# asp.net-mvc dependency-injection ninject

我已经创建了一个新的MVC Web应用程序,并且我引用了Ninject.dll,Ninject.Web.Common.dll和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)
        {
        }        
    }

我收到错误“序列中没有元素”。我做错了什么?

错误详情:

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 个答案:

答案 0 :(得分:40)

要明确说明这一点,如果您使用NuGet添加'Ninject.Mvc3'包(我使用的是3.0.0.6版),那么就不需要对{{>进行任何修改 1}}。通过在MVC 4项目的global.asax.cs文件夹中创建NinjectWebCommon类,NuGet包为您提供了神奇的功能。

我这样说是因为我似乎遵循了原始海报的类似教程(我跟着一篇名为“Dependency Injection in asp.net mvc4 and webapi using Ninject'的代码项目”,并且与原始海报完全相同。代码项目文章没有明确表示您要么使用NuGet(并且不要触摸App_Start 手动添加Ninject引用(并修改global.asax.cs)。

答案 1 :(得分:24)

您来自NinjectHttpApplication而您正在同时使用App_Start。选一个!请阅读docu of Ninject.MVC3了解详情。

答案 2 :(得分:7)

确保您没有引用也使用NinjectMVC3 App_Start的项目。 删除对此类的引用后,我的项目开始工作。此外,如前所述,检查名称空间是否匹配并且是正确的。