Building a MVC2 Template, Part 15, Adding Ninject
Jun 14
.Net, Development Asp.Net Mvc, Nehemiah Project, Ninject No Comments
Our last post saw the creation of two logging services utilizing NLog and Log4Net. In this post we’ll add Ninject to our template and use it to inject the logging service of our choosing.
Let’s not kid ourselves. Most of the development work on an application is done after deployment. No matter how well written the original application is, someone will be replacing part of the application sometime in it’s lifetime. If you’ve ever worked on a project where you’ve had to change the data repository or logging service or email service, you know how frustrating it can be when the core code and your service (i.e. data repository) are tightly knitted together. We touched on this subject in our previous post, Part 14, Services and Interfaces.
For example, lets say you’ve taken this application framework and have built an application that runs on your company’s web servers, in a full trust environment. Your company has invested heavily in instrumentation software that monitors the event logs. The existing logging services don’t write to the event log (actually you can with NLog, but for the purposes of this example, lets assume it’s not available).
So you write a new logging service that implements our ILogger interface and it writes everything to the event log. You’ve tested it and it works perfectly. All that’s left is to replace instances of NLogLogger with EventLogLogger. So you open up your trusty coded editor (Visual Studio or otherwise) and do a global search and replace. Easy right? Are you sure you’ve replaced all occurrences of NLogLogger with EventLogLogger? Did you replace too many occurrences?
What if you could go to a single location and tell your application to use EventLogLogger everywhere it expects to use the ILogger interface? Now, that’s simple. It’s brilliant! You may be asking, “How”? Well, that’s the magic (and promise) of dependency injection.
Building Ninject MVC
Download the Ninject binaries from http://www.ninject.org/download (.Net Framework 3.5). Copy Ninject.dll to C:\_CodeVault\Ninject\version 2.0.
Next download the source code for the MVC extension from http://github.com/ninject/ninject.web.mvc. Build the solution in the mvc2 folder. Copy Ninject.Web.Mvc.dll to C:\_CodeVault\Ninject\version 2.0. You can copy Ninject.dll too if you wish. However it should be identical to the DLL that you copied above.
Using Ninject
All of our code changes will be made to Global.asax.cs. The completed source code is listed below. In the Nehemiah project you’ll need to add a reference to Ninject.dll and Ninject.Web.Mvc.dll. Both DLLs are in C:\_CodeVault\Ninject\version 2.0. After you add these references unload the project and edit the .csproj file. Search for Ninject and make sure the path to the Ninject DLLs is a complete path and not a relative path. You’ll want the path to be “\_CodeVault\Ninject\version 2.0″ instead of “..\..\..\_CodeVault\Ninject\version 2.0″. Your path may be slightly different depending upon where your solution is located.
The first item to change is our MvcApplication class. It will need to inherit from NinjectHttpApplication instead of System.Web.HttpApplication. The use of method Application_Start will be replaced with OnApplicationStarted. In OnApplicationStarted we’ll use an Ninject method to automatically register all of the controllers in our application.
Next we need a class derived from NinjectModule that will setup our bindings. We accomplish this by creating a class WebModule inheriting from NinjectModule. Then we override the Load method. Our bindings are set in the Load method. I included the WebModule class in the Global.asax.cs file because this is the only place it is used.
The NehemiahKernel property simply makes it easier to reference the StandardKernel object.
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;
using Service.Logging;
using Service.Logging.NLog;
namespace Nehemiah
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : NinjectHttpApplication // System.Web.HttpApplication
{
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
);
routes.MapRoute(
"ErrorHandler", // Route name
"{*path}", // URL
new { controller = "Error", action = "Index" }
);
}
// Replaced with the method OnApplicationStarted when using Ninject
//protected void Application_Start()
//{
// AreaRegistration.RegisterAllAreas();
// RegisterRoutes(RouteTable.Routes);
//}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
// Use Ninject to register all of our controllers.
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
NehemiahKernel.Get<ILogger>().Info("Application started");
}
protected override IKernel CreateKernel()
{
return NehemiahKernel;
}
IKernel NehemiahKernel
{
get { return new StandardKernel(new WebModule()); }
}
public class WebModule : NinjectModule
{
public override void Load()
{
// Todo: Put your bindings here.
Bind<ILogger>().To<NLogLogger>().InSingletonScope();
//Bind<ILogger>().To<Log4NetLogger>().InSingletonScope();
}
}
}
}
Notice the line:
NehemiahKernel.Get<ILogger>().Info(“Application started”);
Depending upon which logging service you selected it will write “Application started” to the appropriate log file. The NLogLogger service uses a file different from the Log4NetLogger service. Run the application and check the NLog log file. Then change the logging service to Log4Net, rebuild the solution, and run the application. The Log4Net log file will have an entry for the last time the application ran.
We haven’t fully exploited the dependency injection that Ninject provides. We will do that in follow up posts.
Commit all the code to source control. Then check http://localhost:8080 and verify TeamCity built the project without any errors.
References
- http://www.kevinrohrbaugh.com/blog/2009/8/7/using-ninject-2-with-aspnet-mvc.html
- http://jasondentler.com/blog/2009/08/part-6-ninject-and-mvc-or-how-to-be-a-web-ninja/
Previous Articles in this Series
- Part 1, Introduction
- Part 2, Version Control
- Part 3, Automated Builds
- Part 4, BDD with MSpec
- Part 5, Writing Specs
- Part 6, Writing Specs Continued
- Part 7, Custom Web Errors
- Part 8, Adding a Custom Membership Provider
- Part 9, Adding a Custom Role Provider
- Part 10, Adding a Custom Profile Provider
- Part 11, Finishing the Custom Membership Provider
- Part 12, Finishing the Custom Role Provider
- Part 13, Finishing the Custom Profile Provider
- Part 14, Logging Services













Recent Comments