Ninject And ASP .Net MVC3

I've mentioned Ninject before, it's an excellent dependancy injection framework that lets you keep your code loosely coupled.

I've also mentioned that I've been working with the MVC Framework quite a lot of late, and what's neat is that hooks are provided that make it easy to use your own dependancy injection framework. To that end, this post will be looking at how Ninject can be integrated with MVC3, and why that's awesome!

I'll be working with a clean MVC3 project created in Visual Studio 2010. There are a couple of ways of integrating Ninject; using the IDependancyResolver interface, or inheriting from NinjectHttpApplication.

Option 1: IDependancyResolver

All we need to do here is implement IDependancyResolver and then register an instance of it on application startup.

So a simple implementation for Ninject will look something like this:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using Ninject;
using Ninject.Modules;

public class NinjectResolver : IDependencyResolver
{
IKernel kernel;

public NinjectResolver(INinjectModule[] modules)
{
kernel = new StandardKernel(modules);
}

public object GetService(Type serviceType)
{
return kernel.Get(serviceType);
}

public IEnumerable GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
}

And we register this in Application_Start with a simple call like so:
var resolver = new NinjectResolver(new MyModule());
DependencyResolver.SetResolver(resolver);

MVC3 will then use this object when trying to instantiate an instance of a class, but will fall back to it's built in methods for locating objects if this fails. What this means in practice is that you don't need to worry about registering all of the default objects MVC3 uses such as the controller factory, leaving you free to just deal with the stuff you care about.

Option 2: NinjectHttpApplication

The second option is to make use of Ninject's MVC3 extension which can be found here.

In this case, all we need to do is change our MvcApplication class (found in Global.asax) to inherit from NinjectHttpApplication instead of MvcApplication, and then implement CreateKernel to register the modules we've created.

public class MvcApplication : NinjectHttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}

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
);

}

protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}

public override IKernel CreateKernel()
{
return new StandardKernel(new MyModule());
}
}

And that's it; now Ninject will be used to resolve any dependencies that are requested when the object model is being built.

Which Approach?

But which of the two approaches should you use? It doesn't matter hugely, the first option allows for a very quick integration, you could even register a dependency resolver in a much more concise fashion making use of lambdas like so:
var kernel = new StandardKernel(modules);
DependencyResolver.SetResolver(
t => {
try { return kernel.Get(t); }
catch { return null; }
},
t => kernel.GetAll(t)
);

However, using Ninject's MVC3 extension is marginally more self contained, so I tend to prefer making use of NinjectHttpApplication instead. Note that Ninject will still find the right controllers without registering them, so there is no need to register all your controllers unless you want to add additional configuration to them.

If you think you're likely to want to change your DI framework, then it would make more sense to make use of the IDependancyResolver interface so that you can drop in a quick replacement, although personally I think that scenario is somewhat unlikely.

Now you're loosely coupled

So that's a couple of simple ways to integrate Ninject with MVC3; not too hard to achieve and provides a lot of power and flexibility.

Dependancy Injection And Ninject

I'm going to look at another useful item to have in your developer toolbox today: Dependancy Injection.

What Is It And Why Should I Care?

Dependancy Injection is a pretty large topic in itself, but what it boils down to is breaking down tightly coupled classes by using interfaces to provide a level of indirection. There is a good example of this on the Ninject Wiki.
class Samurai {
readonly Sword _sword;
public Samurai() {
_sword = new Sword();
}
public void Attack(string target) {
_sword.Hit(target);
}
}

If we wanted to break the tight coupling between a Samurai and his sword, to allow the samurai to attack with any weapon, we could do the following:
class Samurai {
private IWeapon _weapon;
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
public void Attack(string target) {
_weapon.Hit(target);
}
}

This allows us to provide the samurai with any weapon that implements the IWeapon interface, removing the tight coupling between the samurai and his weapon. This is the essence of Dependancy Injection.

My framework of choice is Ninject, so let's look at how to setup a project to use it.

Setting Up Ninject

There are two things we need to do to setup Ninject, the first is to setup a module that will register all our dependancies:
class ExampleModule : StandardModule
{
public override void Load()
{
Bind().To();
Bind().To();
}
}

Next thing to do is create a kernel; this acts as a repository that will let us request instances of the types we registered.
IKernel kernel = new StandardKernel();

Example Usage

Now that the setup has been completed, we can access the object repository using the kernel:
Samurai s = kernel.Get();

As the kernel uses generics, we can get a strongly typed result. Now, assuming we used the second class definition of Samurai which has a constructor with an IWeapon argument, we'll receive an instance of a Samurai with a sword weapon. When creating new object instances, Ninject will check what parameters an object's constructor requires, create new instances of each and inject them automatically. This is how we ended up with a Samurai with a sword, as our config specified that when an IWeapon object is required, a Sword should be provided.

This can become massively useful in a number of ways. For example. say you want to add logging to a class, simply include an ILogger in the constructor, and start logging. You don't need to worry about setting up the logger as that's conveniently handled elsewhere. Need to change the method of logging? Change it in the one place and feel a smug satisfaction that you don't need to check through all your code for that one place where you dealt with it differently.

Activation Behaviours

"But what if I don't want a new instance every time?" I hear you ask. Ninject provides some flexibility in how new objects are created through Activation Behaviours.

For example, if we only wanted a single instance of a given class, we could configure it like so:
Bind().To().Using();

Or say we're writing a multi-threaded application, and only wanted one instance of a particular class per thread:
Bind().To().Using();

The other supported behaviours are TransientBehaviour, which is the default and creates a new object every time it is requested; and OnePerRequestBehavior, which will create an object instance once for each web request.

Summary

So hopefully you now have an idea of what Dependancy Injection is, what it can do for you, and how to get a simple application architecture up and running with Ninject.

Ninject provides a lot more flexibility than has been presented here, allowing for much more complex activation scenarios: an entire object graph can be created with a single call to IKernel.Get. When you have an object graph several levels deep, this can really help in ensuring things are created in a consistent manner.

Visual Inheritance With .NET Compact Framework

The idea

Recently I've been working on an MVC framework for the .Net compact framework, partly to aid the re-use of certain visual components, such as signature capture screens etc.

As visual inheritance has been supported for the compact framework from VS2005 this should make it very easy to provide a nice base implementation that can then be customised as required.

To this end I created a simple base frame to handle some common functionality and a number of input frames to handle different tasks.

The Problem

At this point the input frames had text overlaid on them in design mode:

Visual inheritance is currently disabled because the base class references a device-specific component or contains p/invoke

Annoying, as I wanted the design time support of being able to visually edit the frames as required.

The Solution

Initial research turned up an MSDN article that discussed this issue and mentioned a number of causes including P/Invokes and device specific code.

The article also states:

If you are sure that platform invoke will not be executed during design time, you can safely enable visual inheritance by putting a DesktopCompatible(true) attribute on the parent form or the parent user control.

This attribute can be applied in a DesignTimeAttributes.xmta file (added through the add file to solution dialog):



true

And...it still failed. 10 more minutes off hair pulling and I realised that fraLogin inherited from BaseFrame, so I added the attribute to that class too:


true

And now visual inhertance works!

Summary

So in short, if you want visual inheritance when developing with the compact framework, remember to add the DesktopCompatible attribute to any controls that will be derived from.

Concise Invoking into the UI Thread

It's a new year (and has been for a while), so time to get on and actually make use of this blog.

I often find myself having to Invoke execution back in to the UI thread, and thus far the most concise way I have come accross for doing this is as follows:

public void UIFunction(string aMessage)
{
MethodInvoker del = delegate{
lblUILabel.Text = aMessage;
};
Invoke(del);
}

This is nice as it gives you access to the function parameters inside the Invoked anonymous delegate without needing to add them to the invoke call, and also saves you from creating any more functions, whose only purpose is to deal with being invoked.

Obviously you may want to consider that anyway if the logic is complex, but I like that this method keeps things nicely encapsulated in a single function.

The MethodInvoker delegate comes from the Windows.Forms namespace, so if you want to use this method where it is unavailable, such as on the Compact Framework, simply create a new delegate type as follows:
public Delegate void MethodInvoker();