在App_start文件夹中配置Ninject,具体为ninjectwebcommon.cs文件

时间:2014-04-29 16:45:13

标签: c# asp.net-mvc-5

我有一个简单的查询,我正在关注此链接上的教程: http://www.prideparrot.com/blog/archive/2012/12/how_to_create_a_simple_blog_part1#book-unique-identifier 我的问题是本教程的作者在global.asax文件中配置ninject并删除了ninjectwebcommon.cs文件。我正在尝试将justblog集成到我使用ninjectwebcommon.cs文件的现有asp.netMVC5应用程序中。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您是否使用Nuget添加Ninject?您需要引用WebActivatorEx以使引导程序工作(显然与其他所需的Ninject引用一起)。在项目的App_Start文件夹中添加NinjectWebCommon.cs类,如下所示:

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

namespace YourMvcApp.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(); // you'll add modules to the parameter list here
            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)
        //{
        //}
    }
}