#region License // // Authors: Nate Kohari , Josh Close // Copyright (c) 2007-2009, Enkari, Ltd. // // Dual-licensed under the Apache License, Version 2.0, and the Microsoft Public License (Ms-PL). // See the file LICENSE.txt for details. // #endregion #region Using Directives using System.Web; using System.Web.Mvc; using System.Web.Routing; using Ninject.Infrastructure; #endregion namespace Ninject.Web.Mvc { using Ninject.Planning.Bindings.Resolvers; /// /// Defines an that is controlled by a Ninject . /// public abstract class NinjectHttpApplication : HttpApplication, IHaveKernel { private static IKernel _kernel; /// /// Gets the kernel. /// public IKernel Kernel { get { return _kernel; } } /// /// Starts the application. /// public void Application_Start() { lock (this) { _kernel = CreateKernel(); _kernel.Components.RemoveAll(); _kernel.Components.Add(); _kernel.Components.Add(); _kernel.Bind().ToConstant(RouteTable.Routes); _kernel.Bind().ToMethod(ctx => HttpContext.Current).InTransientScope(); _kernel.Bind().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope(); _kernel.Bind().To().InSingletonScope(); ControllerBuilder.Current.SetControllerFactory(CreateControllerFactory()); _kernel.Inject(this); OnApplicationStarted(); } } /// /// Releases the kernel on application end. /// public void Application_End() { lock (this) { if (_kernel != null) { _kernel.Dispose(); _kernel = null; } OnApplicationStopped(); } } /// /// Creates the kernel that will manage your application. /// /// The created kernel. protected abstract IKernel CreateKernel(); /// /// Creates the controller factory that is used to create the controllers. /// /// The created controller factory. protected virtual NinjectControllerFactory CreateControllerFactory() { return new NinjectControllerFactory(Kernel); } /// /// Called when the application is started. /// protected virtual void OnApplicationStarted() { } /// /// Called when the application is stopped. /// protected virtual void OnApplicationStopped() { } } }