Archive for the 'MVC' Category

How to setup Dependency Injection with Microsoft Unity in Asp.net Mvc

Dependency Injection (DI) is a pretty great technique that will help you decouple a service from a client. The way it works, is that when a client is created a service will be applied in the instantiation of the client, so that it holds a reference to the service. You can of course inject multiple services, if you want to.

The description of DI might be a bit vague, because the term service seems to be used for anything these days. I hope the examples will shed some light on it.

Let’s see how things will look like without DI - This can of course be done a bit differently, but for the sake of the example we will just keep it like this.

1
2
3
4
5
6
7
8
9
public class HomeController : Controller
{
	public void Index()
	{
		ISomeRepository repo = new SomeRepository();
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

Let’s move on to an example where DI comes into play.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HomeController : Controller
{
	private ISomeRepository repo;
 
	public HomeController(ISomeRepository someRepository)
	{
		repo = someRepository;
	}
 
	public void Index()
	{
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

We need to do a little bit more than this. So let’s download Unity from Microsoft and include it in our project. Then we can create a new ControllerFactory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class UnityControllerFactory : DefaultControllerFactory
{
	private readonly IUnityContainer _container;
 
	public UnityControllerFactory(IUnityContainer container)
	{
		_container = container;
	}
 
	protected override IController GetControllerInstance(Type controllerType)
	{
		if (controllerType == null)
		{
			throw new HttpException(0x194, "No Controller Found");
		}
 
		if (!typeof(IController).IsAssignableFrom(controllerType))
		{
			throw new ArgumentException("TypeDoesNotSubclassControllerBase", 
				"controllerType");
		}
 
		return _container.Resolve(controllerType) as IController;
	}
}

So far, so good. We will now set it up in the Global.asax file. Of course, you will need to create some sort of service, if you want to test this. In my example I assume that I have a service called SomeRepository available to me, which implements the interface ISomeRepository.

1
2
3
4
5
6
7
8
protected void Application_Start()
{
	IUnityContainer container = new UnityContainer();
	container.RegisterType<ISomeRepository, SomeRepository>();
 
	UnityControllerFactory factory = new UnityControllerFactory(container);
	ControllerBuilder.Current.SetControllerFactory(factory);
}

That’s it! You have now injected your first service into a Controller.

The great thing about this is that you can now unit test your controllers with a mock implementation of a service, as long as it implements the interface.

If you have been using MonoRail, then you probably know about Windsor, so if you don’t like to use Unity, you can easily switch Unity out.

Ps. Using DI can be a good thing, but using it extensively can make things too complex, which is a bad thing.

The SmartDispatcherController in MonoRail will make your life easier

It has been awhile since I last wrote about MonoRail due to a lot of work at my job, but I will try to make up for that with this article and hopefully a few more.

The SmartDispatcherController in MonoRail is one of the things that I really like in the framework, it really increases the speed at witch you can write some of your code – lets take an example.

1
2
3
4
5
<form action="/user/create.rails"> 
  Email: <input type="text" name="email" /> <br />
  Password: <input type="text" name="password" /> <br /><br />
  <input type="submit" value="Create" />
</form>

This looks pretty straight forward, no magic here, so lets take a look at the code that will be executed when you hit the submit button.

1
2
3
4
public void Create(string email, string password)
{
	// Create your user
}

This is where the SmartDispatcherController kicks in, as you can see the parameters in the functions matches the elements from the form and better yet, it will (if capable) convert it to the datatype you have specified – now that`s cool, right!

If you think this is cool, then think about how cool it would be to do this with objects. Let us make a simple class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class User
{
    private string email;
    private string password;
 
    public string Email
    {
        get { return email; }
        set { email = value; }
    }
 
    public string Password
    {
        get { return password; }
        set { password = value; }
    }
}

Nothing fancy here, so moving on to the html.

1
2
3
4
5
<form action="/user/create.rails"> 
  Email: <input type="text" name="user.Email" /> <br />
  Password: <input type="text" name="user.Password" /> <br /><br />
  <input type="submit" value="Create" />
</form>

It looks quite similar to the first html example but if you look a little closer you will see that the name of the input elements is slightly different (adding user). That part will work like a prefix when we parse it to our function.

Time to add some SmartDispatcherController magic.

1
2
3
4
5
public void Create([DataBind("user")]User user)
{
	// Create your user
	user.Create();
}

Now the object and the properties have been populated with the data we entered into the input fields - This is so awesome.

There is no doubt about that this will improve your productivity and I seriously hope that Microsoft will learn from this and add it to their MVC framework.

MVC Framework for C#

When I got into the whole Asp.Net thing, I thought it was pretty nice with all the controls that you could drag`n drop. When I got a bit further into it, I started to get annoyed with how the model works, the complex page lifecycle, the Viewstate and how easy it was to write smelly code (I know you can do this with many languages), and by smelly code I mean that quite a few people thinks that everything should happen in the code behind the file, simply because it removes the focus on how to separate the code correctly.

About 5 months ago a friend told me about this MVC Framework for .NET called MonoRail, which is inspired by Ruby on Rails.
It uses NVelocity as its view engine and NHibernate for persistence and on top of that is has a nice Ajax support that use the awesome PrototypeJs, but it also comes with Script.aculo.us and fValidate.

Pros and cons with MonoRail and Asp.Net

After a few months of using MonoRail I was hooked and whished that Microsoft would have made a framework like this from the beginning. So it was with great joy when I read Scott Gu`s post about them building a MVC Framework. Its fare from ready to be released but it will be interesting to follow the project.

« Previous Page