Source

main / Source / WebClient / Web.Client / Global.asax.cs

using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using DataUp.Web.Common;
using DataUp.Web.DataLayer;
using DataUp.Web.BizLogic;
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.WindowsAzure;

namespace DataUp.Web.Client
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static UnityContainer container;

        /// <summary>
        /// Gets the parent unity container.
        /// </summary>
        public static UnityContainer ParentUnityContainer
        {
            get
            {
                return container;
            }
        }

        protected void Application_Start()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSettingPublisher) =>
            {
                configSettingPublisher(ConfigReader<string>.GetSetting(configName));
            });

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterUnityContainer();
        }

        /// <summary>
        /// Application Initialize 
        /// </summary>
        public override void Init()
        {
            this.EndRequest += this.EndRequestHandler;
            base.Init();
        }

        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 } // Parameter defaults
            );
        }

        /// <summary>
        /// Creates an instance of UnityContainer and registers the instances which needs to be injected
        /// to Controllers/Views/Services, etc.
        /// </summary>
        private static void RegisterUnityContainer()
        {
            container = new UnityContainer();

            container.RegisterType<DataUpEntities>(
                    new PerRequestLifetimeManager(), new InjectionConstructor(ConfigReader<string>.GetSetting("DataUpEntities")));

            RegisterRepositories(container);
            RegisterServices(container);

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }

        /// <summary>
        /// Registers the required repositories which is required for all the controllers.
        /// </summary>
        /// <param name="container">Instance of unity container</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "TODO: Need to refractor.")]
        private static void RegisterRepositories(UnityContainer container)
        {
            if (container != null)
            {
                container.RegisterType<IBlobDataRepository, BlobDataRepository>(new ContainerControlledLifetimeManager());
                container.RegisterType<IDocumentStoreRepository, DocumentStoreRepository>(new PerRequestLifetimeManager());
                container.RegisterType<IUserRepository, UserRepository>(new PerRequestLifetimeManager());
            }
        }

        /// <summary>
        /// Registers the required services which is required for all the controllers.
        /// </summary>
        /// <param name="container">Instance of unity container</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void RegisterServices(UnityContainer container)
        {
            if (container != null)
            {
                container.RegisterType<IBlobService, BlobService>(new ContainerControlledLifetimeManager());
                container.RegisterType<IProfileService, ProfileService>(new PerRequestLifetimeManager());
                container.RegisterType<IUploadService, UploadService>(new PerRequestLifetimeManager());
                container.RegisterType<IDocumentService, DocumentService>(new PerRequestLifetimeManager());
                container.RegisterType<IExcelService, ExcelService>(new PerRequestLifetimeManager());
                container.RegisterType<IRepositoryService, RepositoryService>(new PerRequestLifetimeManager());
            }
        }

        /// <summary>
        /// End request handler
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">event arguments</param>
        private void EndRequestHandler(object sender, EventArgs e)
        {
            // This is a workaround since subscribing to HttpContext.Current.ApplicationInstance.EndRequest 
            // from HttpContext.Current.ApplicationInstance.BeginRequest does not work. 
            IEnumerable<PerRequestLifetimeManager> perRequestManagers =
                container.Registrations
                    .Select(r => r.LifetimeManager)
                    .OfType<PerRequestLifetimeManager>()
                    .ToArray();

            foreach (var manager in perRequestManagers)
            {
                manager.Dispose();
            }
        }
    }
}