Monday, February 22, 2010

Creating an ASP.NET MVC 2 Controller Factory with Ninject

Introduction



Recently I've been getting into Test Driven Development and one useful thing that helps me out with this is making use of the Inversion of control principle. This makes it easy to pass a Mock version of all my services for the purposes of testing.

However this presents a challenge with the standard MVC Controller Factory. It only supports the parameterless contructors. However, one of the great things about ASP.NET MVC (2) is that it allows you to override most aspects of the framework. It doesn't restrict you as much as it's ASP.NET webforms predecessor. So to avoid the so call "Anti Pattern" of having both a Parameterless Constructor for your "Real Services" and an overloaded constructor for your testing/Mock Services, you can follow this guide to create a Controller Factory which uses ninject. Then you'll only have 1 constructor and you'll sleep soundly.

Creating Ninject Controller Factory




  • Now let's create a new MVC 2 Project
  • Once it open's we'll need to add a reference to ninject.core.dll

  • Next, let's create a helper method for our ninject controller factory called NinjectControllerFactory.cs

  • We'll need to inherit from the default controller factory. Mainly so we don't have to re-invent the wheel and we can just override one part of it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NinjectIoc
{
    public class NinjectControllerFactory : DefaultControllerFactory
    {
    }
}

  • For the purposes of this demo we'll need to create an example service and interface, to demo the Ioc process and ninject.

namespace ExampleServices
{
    public interface IExampleInterface
    {
        void Method1();
        string Property1 { get; }
    }

    public class ExampleConcreteClass : IExampleInterface
    {

        #region IExampleInterface Members

        public void Method1()
        {
            // Do Nothing.
        }

        public string Property1
        {
            get
            {
                return "Hello World";
            }
        }

        #endregion
    }
}
  • Now we can setup a ninject Module which returns our ExampleConcreteClass when given the IExampleInterface.
  • We do this by creating a class which inherits from ninjects standardmodule and overrides the Load Method

private class ExampleConfigModule : StandardModule
    {
        public override void Load()
        {
            Bind<IExampleInterface>().To<ExampleConcreteClass>();
        }
    }
  • Finally we'll override the GetControllerInstance Method from the DefaultControllerFactory using ninject to return a controller complete with any parameters in the controllers constructor.
public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel kernel = new StandardKernel(new ExampleConfigModule());

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            // We don't want to pass null to ninject as we'll get a strange error.
            return controllerType == null ? null
                                          : (IController)kernel.Get(controllerType);
        }
    }
  • Now we'll need to tell the MVC 2 framework to use our new Controller Factory insted of the defaultControllerFactory.
  • To do this we'll need to edit the global.asax.cs file
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
            );

            // Setup Our new Controller Factory.
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

        }
  • That's it for the setup. Now we'll need to test it out.
  • Let's update the default Home Controller to include a parameter in it's constructor
public class HomeController : Controller
    {
        #region Testing Our Controller Factory

        private IExampleInterface _example;

        public HomeController(IExampleInterface exampleInterface)
        {
            // Test our our new Ninject Controller Factory
            _example = exampleInterface;
        }

        #endregion

        public ActionResult Index()
        {
            // Will it work?? 
            ViewData["Message"] = _example.Property1;

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }

  • Now if this work's we should see the word's "Hello World" on the home page.

  • Cool. it worked.

Conclusion


It would be very easy to swap out Ninject for another Ioc container. So i hope it helps someone out there. If you want to get a copy of the example code then I've copied it up to my



Enjoy.

62 comments:

  1. I'm not able to download a copy of your example, can you check that your link is good please ?

    ReplyDelete
  2. Hey.. thanks for that. I've updated the link and it works ok now.. please try again ;)

    ReplyDelete
  3. Great post, still cannot get why "Type controllerType" may be null?

    ReplyDelete
  4. The blog gave me idea to create asp net mvc 2 controller My sincere thanks for sharing this post please continue to share this post
    Dot Net Training in Chennai

    ReplyDelete
  5. Excellent post. you have post an very informative information. Keep it up. Salesforce Training in Chennai | Selenium Training in Chennai

    ReplyDelete
  6. Para penjudi akan dengan mudah untuk memenangkan permainan judi ceme keliling. Hanya dengan menggunakan situs ini dan menggunakan cara ini maka para penjudi akan dengan mudah untuk mendapatkan banyak kemenangan
    asikqq
    http://dewaqqq.club/
    http://sumoqq.today/
    interqq
    pionpoker
    bandar ceme terpercaya
    freebet tanpa deposit
    paito warna
    syair sgp

    ReplyDelete
  7. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    Blockchain online training

    ReplyDelete
  8. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog.
    Devops certification training
    Devops online course
    Devops online training
    Devops training course

    ReplyDelete
  9. Thank you for excellent article.You made an article that is interesting.
    AWS Solutions Architect courses in Bangalore with certifications.
    https://onlineidealab.com/aws-training-in-bangalore/


    ReplyDelete
  10. Thank you very much for the details you shared. Kindly try to implement a kind of information through it and keep writing such wonderful things.
    Gym Equipment

    ReplyDelete
  11. Hi, I enjoy your blog. There are a lot of good information on this blog, I'd like to read it and I think people will get a lot of support from this blog. Thank you for sharing this informative blog, please keep up and share some unique posts with us in the future.
    Mobile app development companies
    we are the best Mobile app development company in Bangalore
    Mobile app development company in India
    Mobile app development companies in India

    ReplyDelete
  12. Hi, I enjoy your blog. There are a lot of good information on this blog, I'd like to read it and I think people will get a lot of support from this blog. Thank you for sharing this informative blog, please keep up and share some unique posts with us in the future.
    Mobile app development companies
    we are the best Mobile app development company in Bangalore
    Mobile app development company in India
    Mobile app development companies in India

    ReplyDelete
  13. This is a really explainable very well and i got more information from your site.Very much useful for me to understand many concepts and helped me a lot.Best data science courses in hyerabad

    ReplyDelete
  14. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our site please visit to know more information
    data science training in courses

    ReplyDelete
  15. This is a really very nice post you shared, i like the post, thanks for sharing..

    Data Science Training

    ReplyDelete

  16. First You got a great blog .I will be interested in more similar topics. I see you have really very useful topics, i will be always checking your blog thanks.

    Digital Marketing Training Institutes in Hyderabad


    ReplyDelete
  17. This is an excellent post . thanks for sharing it. It is really what I wanted to see. I hope in the future you will continue to share such an excellent post.
    business analytics course

    ReplyDelete
  18. It's really nice and meaningful. it's a really cool blog.you have really helped lots of people who visit blogs and provide them useful information
    business analytics course

    ReplyDelete
  19. This post is very simple to read and appreciate without leaving any details out. Great work!
    digital marketing courses in hyderabad with placement

    ReplyDelete
  20. A great website with interesting and unique material what else would you need.
    data science training

    ReplyDelete
  21. In essence, a CRM software consultant helps you utilize a powerful tool for managing interactions with existing and potential clients as well as identifying leads. CRM software streamlines communication and increases the efficiency of team responses to clients.

    ReplyDelete
  22. Employees can help clients through DevOps consulting services and solve many real-world problems. Listed below are some examples of how DevOps applications are making an impact in the real world.

    ReplyDelete
  23. Good post. I would like to thank you for the effort you put into writing this interesting and informative article. If you need a visa , you can apply for Turkey Visa and Visa on Arrival Turkey You can fill the form. It is easy & quick to get a Turkey eVisas by following 3 simple steps.

    ReplyDelete
  24. Great article this is really informative and innovative: with new updates.with new updates. It was really valuable. Thanks a lot. Travelers can easily apply for Indian visa online. The Government of India has provided an easy-to-use method to apply for an Indian Visa.

    ReplyDelete

  25. Thanks for sharing this information, Keep it up.... South Africa tourist visa, The Government of South Africa has confirmed that South Africa's new e-Visa system will be implemented for 15 countries by March 2022.

    ReplyDelete
  26. This is a wonderful inspiring article. I am practically satisfied with your great work. You have really put together extremely helpful data. Keep it up.. Are you planning to visit Kenya? For this, you need to fill the Kenya online visa application and pay the fee.

    ReplyDelete
  27. Really an awesome blog and useful content. Keep update more blogs again soon. Thank you.
    Data Science Training in Hyderabad

    ReplyDelete
  28. It's good to be back! I thought I've been to this site before, but after reading some of the posts, I realized it's new to me. In any case, I'm glad I found it and will definitely bookmark it and check back often. how to get India visa, You can apply for an Indian visa online through the India visa website.

    ReplyDelete
  29. I have bookmarked your site since this site contains significant data in it. You rock for keeping incredible stuff. I am a lot of appreciative of this site.

    ReplyDelete
  30. 360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.

    ReplyDelete
  31. Thank you for sharing this kind of information about programming languages. I highly recommended Flutter App Development Company. This is the latest technology used by many programmers.

    ReplyDelete
  32. Google wants end users. An expert digital marketing agency in London can help you understand this better. So, Google can find the answer you are looking for, and you can trust the results you see. If Google thinks both are true, it ranks websites up and down based on queries. By placing something high in the search rankings, Google effectively guarantees the source.

    ReplyDelete
  33. Hii sir, Nice blog. Thanks for sharing. Lots of people query, What is the Indian passport photo size? You can read info about India visa photo requirements via our Indian visa page.

    ReplyDelete
  34. Hello everyone, Foreign citizens can enter India for business purposes. Indian government allows foreign country citizens they can can be apply for e business visa for India. e Business Visa India, Non-Indian visitors who are looking for business business or meetings, setting up industrial or business enterprises in India or other similar business activities etc.

    ReplyDelete
  35. Create innovative, human-centric apps for better customer retention & conversions at the best rate with CronJ's react js development services!

    ReplyDelete

  36. It would help if you thought that the data scientists are the highest-paid employees in a company.
    data science course in kochi

    ReplyDelete
  37. I love the way you explain your article. It's easy to read and understandable. I want to know articles like this. People have the option to apply for a e visa Turkey online which is a hassle free process. And its time and cost saving also.

    ReplyDelete
  38. We have had the experience of using mvc design when undergoing digital transformation, by actually hiring dedicated developers who committed to deliver a similar project.

    ReplyDelete
  39. Such a wonderful blog! This is really superb and thanks for your sharing with us...
    preliminary protective order
    contract dispute resolution process

    ReplyDelete
  40. Video poker requires plenty of strategic thinking, so don't play if you're 우리카지노 drained. We additionally advise you to comply with our video poker ideas for profitable. Gambling movies have gained a lot of reputation over the past few years, however unfortunately, there aren't many that concentrate on} video poker.

    ReplyDelete
  41. India e Visa for Andorra Citizens. For inhabitants of Andorra, India offers e-Visa services, making it easier for them to enter the nation for a variety of reasons. If you are an Andorran citizen planning a trip to India, you can apply for an e-Visa on the official website of the Indian government.

    ReplyDelete
  42. Top things to do in Konya. One of the top things to do in Konya is to visit the iconic Mevlana Museum, dedicated to the famous poet and philosopher, Rumi. Here, visitors can explore the exhibits that showcase Rumi's life and teachings, and witness the mesmerizing whirling dervishes ceremony, a spiritual dance performance unique to Konya.

    ReplyDelete
  43. Kenya Positioned to Embrace the Role of Africa's Singapore. Kenya has the ability to play a significant role in the development of the continent thanks to its advantageous geographic location, stable political environment, and expanding economy.

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. Your openness in providing your knowledge and thoughts is really admirable and highly valued. Your work advances our understanding. The Worlds Most Powerful Passports In 2023 are those that provide its users the most flexibility when traveling. These passports allow travelers to enter several nations without a visa or with one upon arrival. The strongest passports come from nations like Japan, Singapore, Germany, and South Korea, giving its people access to a wide range of travel options. One of these passports can make travel arrangements easier and provide entry to a variety of locations, facilitating exploration of the world.

    ReplyDelete
  46. I'm excited about showcasing excerpts from your articles on my blog. I guarantee full credit will be provided, along with proper source acknowledgment. Given our shared interests, I'm confident that your content would enhance my audience's interaction. Your collaboration would be invaluable. Thank you. Azerbaijan evisa requirements for US citizens, For those planning to visit Azerbaijan, it's essential to be aware of the eVisa requirements. Ensure you have a valid passport, complete the online application, and provide necessary documents such as a passport scan and photo to obtain your eVisa efficiently.

    ReplyDelete