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
- Firstly go here http://ninject.org/download
- Then click on the Release version of ninject.
- Extract the zip to a folder of your choice.
- If you haven't already downloaded MVC please do so from http://www.microsoft.com/downloads/details.aspx?FamilyID=7aba081a-19b9-44c4-a247-3882c8f749e3&displaylang=en#filelist
- 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.
I'm not able to download a copy of your example, can you check that your link is good please ?
ReplyDeleteHey.. thanks for that. I've updated the link and it works ok now.. please try again ;)
ReplyDeleteGreat post, still cannot get why "Type controllerType" may be null?
ReplyDeleteThe blog gave me idea to create asp net mvc 2 controller My sincere thanks for sharing this post please continue to share this post
ReplyDeleteDot Net Training in Chennai
Excellent post. you have post an very informative information. Keep it up. Salesforce Training in Chennai | Selenium Training in Chennai
ReplyDeletegreat
ReplyDeleteGreat Post Thanks for sharing
ReplyDeleteVMware Training in Chennai
DevOps Training in Chennai
DevOps Certification in Chennai
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
ReplyDeleteasikqq
http://dewaqqq.club/
http://sumoqq.today/
interqq
pionpoker
bandar ceme terpercaya
freebet tanpa deposit
paito warna
syair sgp
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.
ReplyDeleteBlockchain online training
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.
ReplyDeleteDevops certification training
Devops online course
Devops online training
Devops training course
Thank you for excellent article.You made an article that is interesting.
ReplyDeleteAWS Solutions Architect courses in Bangalore with certifications.
https://onlineidealab.com/aws-training-in-bangalore/
Thanks for sharing nice information and it is really helpful to me
ReplyDeleteTop Mobile App Development Company in Saudi Arabia
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.
ReplyDeleteGym Equipment
Hey ,Thank you for sharing information
ReplyDeleteTop mobile app development companies in Singapore
Mobile app development companies in Sydney
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.
ReplyDeleteMobile 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
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.
ReplyDeleteMobile 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
This is a awesome blog keep writing such blogs will be waiting to read more
ReplyDeleteMobile application development in India
Mobile application development in Dubai
Mobile application development in Bangalore
Tenride Car
ReplyDeleteThis 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
ReplyDeleteI really enjoyed reading your blog. Great blog
ReplyDeletecommon errors
artificial intelligence future scope
angularjs charts
benefits of rpa
angularjs interview questions and answers for experienced
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
ReplyDeletedata science training in courses
Vé máy bay Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ giá bao nhiêu
vé máy bay tết
vé máy bay đi San Francisco giá rẻ 2021
giá vé máy bay đi Pháp của Vietnam Airline
giá vé máy bay đi Anh Vietnam Airline
vé máy bay từ Hà nội đi Los Angeles
combo du lịch đà nẵng
combo đà lạt 4 ngày 3 đêm
visa trung quoc 1 nam
dịch vụ cách ly khách sạn trọn gói
Information that you provide is good and thanks for sharing
ReplyDeletemobile app development company
web app development company
cloud app development company
saas app development company
custom mobile app & web app development company
mobile app and web app maintenance services
seo services | seo company
digital marketing company
Paid marketing services | ppc service providers
NICE SHARE ELLA JAMES
ReplyDeleteThis is a really very nice post you shared, i like the post, thanks for sharing..
ReplyDeleteData Science Training
Wow, amazing post! Really engaging, thank you.
ReplyDeletebest data analytics training in yelahanka
ReplyDeleteFirst 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
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.
ReplyDeletebusiness analytics course
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
ReplyDeletebusiness analytics course
This post is very simple to read and appreciate without leaving any details out. Great work!
ReplyDeletedigital marketing courses in hyderabad with placement
A great website with interesting and unique material what else would you need.
ReplyDeletedata science training
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.
ReplyDeleteEmployees 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.
ReplyDeleteGood 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.
ReplyDeleteGreat 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
ReplyDeleteThanks 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.
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.
ReplyDeletePayroll Software
ReplyDeletepayroll software singapore
Really an awesome blog and useful content. Keep update more blogs again soon. Thank you.
ReplyDeleteData Science Training in Hyderabad
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
ReplyDeleteorganic chemistry notes
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.
ReplyDelete360DigiTMG, 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.
ReplyDeleteThank 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.
ReplyDeleteGoogle 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.
ReplyDeleteHii 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.
ReplyDeleteHello 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.
ReplyDeleteCreate innovative, human-centric apps for better customer retention & conversions at the best rate with CronJ's react js development services!
ReplyDelete
ReplyDeleteIt would help if you thought that the data scientists are the highest-paid employees in a company.
data science course in kochi
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.
ReplyDeletenice and useful post
ReplyDeleteBest Website Development Company In Hyderabad
nice post.keep it up..
ReplyDeleteBest Website Development Company In Hyderabad
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하동콜걸마사지
ReplyDelete산청콜걸마사지
거창콜걸마사지
합천콜걸마사지
군위콜걸마사지
의성콜걸마사지
영양콜걸마사지
청도콜걸마사지
고령콜걸마사지
Such a wonderful blog! This is really superb and thanks for your sharing with us...
ReplyDeletepreliminary protective order
contract dispute resolution process
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.
ReplyDeleteIndia 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.
ReplyDeleteTop 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.
ReplyDeleteKenya 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.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteYour 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.
ReplyDeleteI'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