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

Med*_*tor 26 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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)
        {
        }        
    }
Run Code Online (Sandbox Code Playgroud)

我收到错误"序列不包含任何元素".我究竟做错了什么?

错误详情:

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
Run Code Online (Sandbox Code Playgroud)

小智 40

为了这个明确清楚,如果你用的NuGet加入"Ninject.Mvc3"包(我使用的版本3.0.0.6),有没有必要进行任何修改global.asax.cs.通过NinjectWebCommonApp_StartMVC 4项目的文件夹中创建类,NuGet包为您提供了神奇的功能.

我这样说是因为我似乎跟着原始海报的类似教程(我跟着一篇关于代码项目的文章,名为' asp.net mvc4中依赖注入和使用Ninject的webapi'),并且与原始版本完全相同海报.该代码项目文章没有说清楚,你应该要么使用的NuGet(不要触摸global.asax.cs 手动添加Ninject引用(和修正global.asax.cs).


Rem*_*oor 24

您是从NinjectHttpApplicationAND同时使用AND 派生的App_Start.选一个!阅读Ninject.MVC3文档以获取更多信息.

  • @Remo Gloor - 我不得不说这两种不同的方法对于初学者来说甚至与文档相比都令人难以置信.文档确实基本上说'它们完全相同',但是看看Nuget方式的代码有一个空的'RegisterServices'方法,而NinjectHttpApplication方式有'kernal.Load(Assembly.GetExecutingAssemby)'.这些不一样,非常感谢对该文档页面的更多指导.这是人们可能在Ninject上找到的第一页,其中一些细节对于初学者来说会很棒 (5认同)
  • 我想看一个访问通过NinjectWebCommon类创建的内核的示例.我有一个自定义控制器工厂,我在尝试找出可以从中访问此内核实例的地方时遇到问题. (2认同)

dwb*_*ito 7

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