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 ?
ReplyDeleteThe effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Project Centers in Chennai.
DeleteSoftware management seeks for decision support to identify technologies like JavaScript that meet best the goals and characteristics of a software project or improvement programme. JavaScript Training in Chennai Accessible experiences and repositories that effectively guide that technology selection are still lacking.
Aim of technology domain analysis is to describe the class of context situations (e.g., kinds of JavaScript software projects) in which a software engineering technology JavaScript Training in Chennai can be applied successfully
Hey.. 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
ReplyDeleteHi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
ReplyDeleteor Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.
Interesting post! This is really helpful for me. I like it! Thanks for sharing!
ReplyDeleteMobile application developers in Chennai | PHP developers Chennai
Thanks for sharing this niche useful informative post to our knowledge.
ReplyDeletebrochure designers in chennai | brochure design company in chennai
Great Post Thanks for sharing
ReplyDeleteVMware Training in Chennai
DevOps Training in Chennai
DevOps Certification in Chennai
Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
ReplyDeleteCheck out the best
home office desks nz
coffee table nz
bookshelves
balance bike
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
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.
ReplyDeleteJob Openings in Chennai
job vacancy in chennai
Pega Training in Chennai
Oracle Training in Chennai
Embedded System Course Chennai
Linux Training in Chennai
Unix Training in Chennai
Power BI Training in Chennai
Oracle DBA Training in Chennai
Tableau Training in Chennai
Spark Training in Chennai
Nice Post. If you wish to get study abroad in any course. The below information will suit you.
ReplyDeleteSkolarrssolutions
Mbbs in Russia
Mbbs in UK
Mbbs in Malaysia
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
Great blog thanks for sharing Looking for the best creative agency to fuel new brand ideas? Adhuntt Media is not just a digital marketing company in chennai. We specialize in revamping your brand identity to drive in best traffic that converts.
ReplyDeleteNice blog thanks for sharing Choosing the right place to buy your first plant isn’t that hard of a choice anymore. Presenting the best plant nursery in Chennai - Karuna Nursery Gardens is proud to showcase more than 3000+ plants ready to be chosen from.
ReplyDeleteExcellent blog thanks for sharing Run your salon business successfully by tying up with the best beauty shop in Chennai - The Pixies Beauty Shop. With tons of prestigious brands to choose from, and amazing offers we’ll have you amazed.
ReplyDeleteAwesome blog thanks for sharing While choosing your perfect ride for driving, Accord Cars comes with and the best packages for you to pick from. Car rentals for self drive in Chennai are done the easier. Just pick out your plan from hourly, daily, weekly and even monthly plans available.
ReplyDeleteVery useful blog thanks for sharing With over a three decade of beauty expertise at our fingertips, we believed that everyone has the right to be beautiful. And so began the journey of our very own Pearl’s Beautician course in Chennai.
ReplyDeleteI 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
This is a nice post in an interesting line of content.Thanks for sharing this article, great way of bring this topic to discussion.
ReplyDeleteMobile Application Development Company In Bangalore
App Development Company In India
Android App Development In Bangalore
Mobile App Development Company in Chennai
I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for thizs article. blockchain online training
ReplyDeleteThank 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/
Awesome blog thankks for sharing 100% virgin Remy Hair Extension in USA, importing from India. Premium and original human hair without joints and bondings. Available in Wigs, Frontal, Wavy, Closure, Bundle, Curly, straight and customized color hairstyles Extensions.
ReplyDeleteVery useful blog thanks for sharing IndPac India the German technology Packaging and sealing machines in India is the leading manufacturer and exporter of Packing Machines in India.
ReplyDeleteGreat Article. Thank you for sharing! Really an awesome post for every one.
ReplyDeleteProject Centers in Chennai
JavaScript Training in Chennai
Final Year Project Domains for IT
JavaScript Training in Chennai
Very useful information...
ReplyDeleteinplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
Australia hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
australia web hosting
denmark web hosting
nice..
ReplyDeleteinplant training in chennai
inplant training in chennai
inplant training in chennai for it
hosting
india hosting
india web hosting
iran web hosting
technology 11 great image sites like imgur hosting
final year project dotnet server hacking what is web hosting
macao web hosting
Please refer below if you are looking for best Online job support and proxy interview from India
ReplyDeleteDevOps Online Job Support From India | PHP Online Job Support From India | Selenium Online Job Support From India | Hadoop Online Job Support From India | Java Online Job Support From India | Angular Online Job Support From India | Python Online Job Support From India | Android Online Job Support From India
Thank you for excellent article.
Very Nice...
ReplyDeleteinternship in chennai for ece students with stipend
internship for mechanical engineering students in chennai
inplant training in chennai
free internship in pune for computer engineering students
internship in chennai for mca
iot internships
internships for cse students in
implant training in chennai
internship for aeronautical engineering students in bangalore
inplant training certificate
very nice post thanks blog.........
ReplyDeleter programming training in chennai
internship in bangalore for ece students
inplant training for mechanical engineering students
summer internships in hyderabad for cse students 2019
final year project ideas for information technology
bba internship certificate
internship in bangalore for ece
internship for cse students in hyderabad
summer training for ece students after second year
robotics courses in chennai
nice...
ReplyDeleteslovakia web hosting
timor lestes hosting
egypt hosting
egypt web hosting
ghana hosting
iceland hosting
italy shared web hosting
jamaica web hosting
kenya hosting
kuwait web hosting
nice.....it is use full...
ReplyDeleteaeronautical internship in india
free internship in chennai for mechanical engineering student
architectural firms in chennai for internship
internship in coimbatore for eee
online internships for cse students
mechanical internship certificate
inplant training report
internships in hyderabad for cse
internship for mba students in chennai
internship in trichy for cse
Thanks for sharing nice information and it is really helpful to me
ReplyDeleteTop Mobile App Development Company in Saudi Arabia
vidmate
ReplyDeleteawesome post presented by you..your writing style is fabulous and keep update with your blogs.
ReplyDeleteMobile Application Development Company in Bangalore
Mobile App Development Companies in Mumbai
Top Mobile App Development Companies in Chennai
It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
ReplyDeletehttp://chennaitraining.in/bi-bw-training-in-chennai/
http://chennaitraining.in/solidworks-training-in-chennai/
http://chennaitraining.in/autocad-training-in-chennai/
http://chennaitraining.in/ansys-training-in-chennai/
http://chennaitraining.in/revit-architecture-training-in-chennai/
http://chennaitraining.in/primavera-training-in-chennai/
Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care
ReplyDeletehttp://chennaitraining.in/creo-training-in-chennai/
http://chennaitraining.in/building-estimation-and-costing-training-in-chennai/
http://chennaitraining.in/machine-learning-training-in-chennai/
http://chennaitraining.in/data-science-training-in-chennai/
http://chennaitraining.in/rpa-training-in-chennai/
http://chennaitraining.in/blueprism-training-in-chennai/
Best Corporate Video Production Company in Bangalore and top Explainer Video Company in Bangalore , 3d, 2d Animation Video Makers in Chennai
ReplyDeleteNice article. Very much informative. Keep writing and share information
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
awesome post presented by you..your writing style is fabulous and keep update with your blogs.
ReplyDeleteMobile App Development Company in Bangalore
Mobile App Development Companies in Mumbai
Mobile App Development Company in Delhi
Top Mobile App Development Companies in Chennai
awesome post presented by you..your writing style is fabulous and keep update with your blogs.
ReplyDeleteMobile App Development Company in Bangalore
Mobile App Development Companies in Mumbai
Mobile App Development Company in Delhi
Top Mobile App Development Companies in Chennai
This is a very nice article we consider your effort of collecting the information and putting it in words as amazing also take a look at our services
ReplyDeleteBest mobile app development companies in India
Best ios app development companies in New Delhi
This is a very good article and nice collection of information , would love to read more of such blogs and also know our services
ReplyDeleteMobile application development in India
Mobile application development in Delhi
Hey ,Thank you for sharing information
ReplyDeleteTop mobile app development companies in Singapore
Mobile app development companies in Sydney
tank you for sharing.
ReplyDeletemobile app development company in Dubai
mobile app development company in Dubai
mobile app development company in Saudi Arabia
mobile app development company in Kuwait
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
aws training in chennai
ReplyDeletePython training in Chennai
data science training in chennai
hadoop training in chennai
machine learning training chennai
Tenride Car
ReplyDeleteThanks for sharing this
ReplyDeleteData Science Course In Hyderabad
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
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
iot training in chennai - IoT Training in Chennai - IoT is one of the technologies which has a lot of scope at the very same time very less number of skilled employees in this technology which means this particular technology will give a huge success rate. Join the Best IOT Training Institute in Chennai now.
ReplyDeleteDevops training Institute in Chennai - DevOps a combination of Development and operations has an better career .Jobs opportunities are there from startup companies to big mnc. Start to learn DevOps technology soon and secure your job now.
blue prism training in Chennai - If you choose to learn the blue prism or automation tool you are supposed to have the programming language. start to learn the blue prism training from the Best Blue prism Training Institute in Chennai.
uipath training in Chennai - UI path technology is one of the fastest developing fields which has a lot of job opportunities such as software developer, Programmer and lot more. Join the Best Uipath Training Institute in Chennai.
microsoft azure training in chennai -Microsoft azure technology is growing and soon it will be competitive aws. So students who start to learn Microsoft azure now will be well - paid in the future. Start to learn Microsoft azure training in Chennai.
Chennai IT Training Center
This is a great motivational article. In fact, I am happy with your good work. They publish very supportive data, really. Continue. Continue blogging. Hope you explore your next post
ReplyDeletedata scientist certification
Great Blog to read, It gives more useful information. Thank lot.
ReplyDeleteOnline Training for Big Data
best Apache Spark online course
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
The information given in this article is very good and I like it. I have also written this kind of blog you can also read for more knowledge.
ReplyDeletewhy cloud computing is needed
benefits of machine learning
benefits of devops
php vs .net
js interview questions
ethical hacking interview questions