Click here to Skip to main content
15,886,362 members
Articles / Web Development / ASP.NET

ASP.NET MVC Controller Dependency Injection for Beginners

Rate me:
Please Sign up or sign in to vote.
4.82/5 (129 votes)
31 Dec 2013CPOL9 min read 628.5K   4.7K   216  
In this article I demonastrate a very simple and straightforward way to inject controller dependency to ASP.NET MVC framework with constructor.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Mvc4.Components;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

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

    public class MvcApplication : System.Web.HttpApplication
    {
        private readonly CompositionContainer _composition;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            //RegisterCustomControllerFactory();
            RegisterMef();

        }

        private void RegisterCustomControllerFactory()
        {
            //IControllerFactory factory = new CustomControllerFactory("Mvc4.Controllers");
            IControllerFactory factory = new CustomControllerFactory();
        }

        private void RegisterMef()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var composition = new CompositionContainer(catalog);
            IControllerFactory mefControllerFactory = new MefControllerFactory(composition);
            ControllerBuilder.Current.SetControllerFactory(mefControllerFactory);
        }
    }
}

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
Architect
Bangladesh Bangladesh
How do I describe myself to you? How can I explain that this is true?
I am who I am because of you! My work I love you !!

Comments and Discussions