C# 如何在 ASP.NET MVC Web 应用程序中使用 Ninject?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10311450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 13:18:05  来源:igfitidea点击:

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

c#asp.net-mvcdependency-injectionninject

提问by Mediator

I've created a new MVC Web application and I have references to Ninject.dll, Ninject.Web.Common.dll and Ninject.Web.MVC.dll.

我创建了一个新的 MVC Web 应用程序,并且引用了 Ninject.dll、Ninject.Web.Common.dll 和 Ninject.Web.MVC.dll。

Global.asax.cs:

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:

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

采纳答案by Remo Gloor

You are deriving from NinjectHttpApplicationAND you are using App_Startat the same time. Choose one! Read the docu of Ninject.MVC3for more info.

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

回答by Duncan Awerbuck

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 modificationsto global.asax.cs. The NuGet package does the magic for you by creating the NinjectWebCommonclass in the App_Startfolder of your MVC 4 project.

为了明确说明这一点,如果您使用 NuGet 添加“Ninject.Mvc3”包(我使用的是 3.0.0.6 版),则无需global.asax.cs. NuGet 包通过NinjectWebCommonApp_StartMVC 4 项目的文件夹中创建类来为您创造奇迹。

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 eitheruse NuGet (and don't touch global.asax.csoradd the Ninject references manually (and amend global.asax.cs).

我这么说是因为我似乎遵循了与原始海报类似的教程(我遵循了关于 The Code Project 的一篇文章,名为“ Dependency Injection in asp.net mvc4 and webapi using Ninject”),并且遇到了与原始海报完全相同的问题海报。该代码项目文章没有说清楚,你应该要么使用的NuGet(不要触摸global.asax.cs手动添加Ninject引用(和修正global.asax.cs)。

回答by dwbrito

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.

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