Click here to Skip to main content
15,879,326 members
Articles / Web Development / CSS

Basics of ASP.NET MVC 3: Part-III (Dependency Injection)

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
26 Mar 2012CPOL2 min read 50.6K   1.1K   29  
Explains basic information and steps for creating an MVC3 application with the Dependency Injection (DI) pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using MVC3Demo.Models;
using MVC3Demo.Controllers;
using MVC3Demo.Factories;

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

    public class MvcApplication : System.Web.HttpApplication
    {
        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 = "Product", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterType();
        }
        private void RegisterType()
        {
            UnityContainer container = new UnityContainer();
            container.RegisterType<IProductModel, ProductModel>();
            container.RegisterType<IController, ProductController>("Product");

            UnityControllerFactory factory = new UnityControllerFactory(container);

            ControllerBuilder.Current.SetControllerFactory(factory);

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Artha is a Technical Lead in Windows Phone, WPF [MVVM, PRISM], ASP.NET [MVC 3.0 & 4.0], C#.NET, VB.NET and ASP.

Windows Phone

Microsoft Developer Network


Published Tools in Visual Studio Galleries


Published Source Codes in CodePlex


Microsoft Virtual Academy Profile


Published Articles in Code Project


Microsoft Certified Professional Developer (MCPD) Microsoft ASP.NET Developer 3.5 (070-564, 070-536, 070-562, 070 315)

Comments and Discussions