You are currently browsing the monthly archive for July 2008.

In our last post we implemented a controller which grabbed a list of books and passed them over to the view to display them. In this post we are going to move that grabbing of a list of books into something else and see how WIndsor can help us out.

So our current list of books is retrieved as below:

   1: public void Index()
   2: {
   3:     List<Book> books = new List<Book>();
   4:     books.Add(new Book("Our First Development Book", "This is our first development book to go into our list of books"));
   5:     books.Add(new Book("The Pragmatic Programmer", "A fantastic book that is as relevant today as it was yesterday. Highly recommended."));
   6:     books.Add(new Book("Working Effectively with Legacy Code", "Another fantastic book which now applies to this application as we aren't writing tests."));
   7:     PropertyBag["books"] = books;
   8: }

We would like to refactor this so that the controller wasn’t responsible for getting this list directly but instead worked with something else to get this listing. My preferred way would be to access this list from a BookRepository like so:

   1: public void Index()
   2: {
   3:     List<Book> books = bookRepository.GetAllBooks();
   4:     PropertyBag["books"] = books;
   5: }

But where do we get bookRespository from? One way would be to new up an instance directly but doing so would hide the dependency that BookController has on BookRepository. But here we can lean on the WIndsor integration and use the Dependency Injection pattern to push our dependencies into our controller (while at the same time making it clear that our controller has a dependency on BookRepository).

Our first step is to create our new BookRepository and move our current book listing to it. It doesn’t really fit within any of the structure the Monorail wizard generated for us (although Models would be the best match) so I’m creating it under a newly added Services folder.

   1: public class BookRepository
   2: {
   3:     public IList<Book> GetAllBooks()
   4:     {
   5:         IList<Book> books = new List<Book>();
   6:         books.Add(new Book("Our First Development Book", "This is our first development book to go into our list of books"));
   7:         books.Add(new Book("The Pragmatic Programmer", "A fantastic book that is as relevant today as it was yesterday. Highly recommended."));
   8:         books.Add(new Book("Working Effectively with Legacy Code", "Another fantastic book which now applies to this application as we aren't writing tests."));
   9:         return books;
  10:     }
  11: }

Now we can add a constructor to our controller that caches the passed in BookRepository instance like so:

   1: public class BookController : BaseController
   2: {
   3:     private readonly BookRepository bookRepository;
   5:     public BookController(BookRepository bookRepository)
   6:     {
   7:         this.bookRepository = bookRepository;
   8:     }
  10:     public void Index()
  11:     {
  12:         List<Book> books = bookRepository.GetAllBooks();
  13:         PropertyBag["books"] = books;
  14:     }
  15: }

So now we have moved our book retrieval out into its own class and made our dependency on this new class explicit via our constructor in the controller. If we hit F5 and view our page we get a “Can’t create component ‘book.controller’ as it has dependencies to be satisfied.” error like below:

Cant create component book.controller as it has dependencies to be satisfied

The reason for this is that, as it says, the BookController depends on BookRepository which was not registered. This is because when Monorail invokes our BookController it does so through Windsor which then resolves our dependencies for us.

Registering our BookRepository is handled in a similar way to which we registered our controller by adding our new BookRepository to components.config in the config folder. All dependencies that aren’t controllers will need to be registered in this file.

If we open up components.config you will see an empty components element. In this we add a component node for our new BookRepository:

<component id="bookRepository"
	type="BookLendingService.Services.BookRepository, BookLendingService" />

Now that we have registered both our component and controller then Windsor can resolve our dependencies for us. So if we hit F5 and view our page we should now see the exact same page we had before we moved the book listing logic.

So we can start to see where the Windsor integration allows us to benefit from dependency injection. As another example we should really introduce an interface for our BookRepository and get the controller to depend on this rather than on the implementation. This allows us to easily mock our dependencies when we test our controllers.

To do this, first extract the interface from our BookRepository (with it’s only member at the moment) and then change BookRepository to implement the interface. Now update BookController to change all uses of BookRepository to IBookRepository, and finally, a change to the components.config file to add a service attribute:

<component id="bookRepository"
	service="BookLendingService.Services.IBookRepository, BookLendingService"
	type="BookLendingService.Services.BookRepository, BookLendingService" />

If you build and view the page again then we should still see our list of books as before but now we are depending on interfaces rather than our implementations.

In our next post we will lean on Windsor even more by enabling auto registration of our controllers and components/services. To do this we will also need to upgrade our Monorail assemblies to a later version which we will also cover.


We’ve downloaded and installed Monorail and had a look at the solution that the wizard generated for us. Now we are going to add a new controller.

In this series of posts we will start to build an application but for now I just want to see what is involved with adding a new controller and associated views and maybe lean on the Windsor integration a bit. As we move towards building our application we will move over to a test first driven approach and explore how testable Monorail is.

So for now, without further ado, let’s add a new controller.

The application I want to build through this series is going to be a book lending service. I have a load of development focused books that I recommend and lend to colleagues at the contracts I work at but I occasionally forget who I’ve lent books too so this application will help relieve this burden (and we’ll see if we can add some real value to the app as we progress).

So for now I would like a way of just taking in a list of Books (our model) and show them in the view, all the while coordinating this activity through the controller.

So first up, we’ll create a BookController and we’ll inherit from BaseController for now. We’ll then add an Index method. You should now have this very empty controller:

   1: namespace BookLendingService.Controllers
   2: {
   3:     public class BookController : BaseController
   4:     {
   5:         public void Index()
   6:         {
   8:         }
   9:     }
  10: }

We now need to add the associated view by adding a new folder under Views called Book and then we need to add an Index.vm file. Add it as a text file so it is empty.

Now we’ll build it and view the site by navigating to /book/index.castle. We should expect to see a page with just the existing layout applied to it as we are inheriting from BaseController. Instead, we get an error page.

Controller not found. Area  Controller Name book - Windows Internet Explorer

The reason for this is that because we enabled the Windsor integration we now need to register our controllers into the container. Castle Windsor is an Inversion of Control container for enabling us to use Dependency Injection. This will help resolve our dependencies but for now we have introduced a slight bit of pain (for long term gain) by adding an extra step to the process.

The Windsor configuration is held under the config folder. The one we need to add to is the controllers.config file. Open it up and add the following line:

<component id="book.controller" type="BookLendingService.Controllers.BookController, BookLendingService" />

You’ll need to change BookLendingService to whatever you’ve called your application but apart from that you should now be able to build the app again and view the page.


Now we’ll extend this to get a list of books, so we need to introduce our Book model. For now our book will have a title and description. This new Book class will be added to the Models folder:

   1: namespace BookLendingService.Models
   2: {
   3:     public class Book
   4:     {
   5:         private string title;
   6:         private string description;
   8:         public Book()
   9:         {
  10:         }
  12:         public Book(string title, string description)
  13:         {
  14:             this.title = title;
  15:             this.description = description;
  16:         }
  18:         public string Title
  19:         {
  20:             get { return title; }
  21:             set { title = value; }
  22:         }
  24:         public string Description
  25:         {
  26:             get { return description; }
  27:             set { description = value; }
  28:         }
  29:     }
  30: }

In our controller we’ll just create a dummy list of books within the index method and assign it to a books property bag item.

   1: using System.Collections.Generic;
   2: using BookLendingService.Models;
   4: namespace BookLendingService.Controllers
   5: {
   6:     public class BookController : BaseController
   7:     {
   8:         public void Index()
   9:         {
  10:             List<Book> books = new List<Book>();
  11:             books.Add(new Book("Our First Development Book", "This is our first development book to go into our list of books"));
  12:             books.Add(new Book("The Pragmatic Programmer", "A fantastic book that is as relevant today as it was yesterday. Highly recommended."));
  13:             books.Add(new Book("Working Effectively with Legacy Code", "Another fantastic book which now applies to this application as we aren't writing tests."));
  14:             PropertyBag["books"] = books;
  15:         }
  16:     }
  17: }

And in our view (book/index.vm) we can now iterate over our collection of books and display them in the view.

   1: <h1>Our Book Listing</h1>
   3: <ul>
   4: #foreach ($book in $books)
   5:     <li>$book.Title</li>
   6: #end
   7: </ul>

And a quick build and refresh of our page gives us our listing of books by title.


And that’s it. We’ve now added our first controller, an initial view for listing out our books, and a starting book model. At the moment it is very raw but we have something we can expand upon.

I think the next post (it’s running late and I’m not working to a set plan here – so is likely to change) will be looking at moving out how we get our list of books in the controller into a BookRepository, wiring that up via Windsor, and maybe seeing if we can get rid of some of the configuration pain by using auto registration of our controllers.

We’ve now run through the initial wizard to get our starting Monorail application up and running. We’re now going to explore what the wizard has generated for us.

Solution StructureSolutionExplorer

Here’s our generated solution with our web project and our test project. Monorail is an MVC web framework and the wizard has generated a project structure for us for containing our Models, Views and Controllers. We also have a folder for static content and the Windsor integration has given us a config folder.

Our Models folder contains our starting business objects/entities. As our application grows, these might get pushed out into their own project to form a domain model or they may stay as a presentation model. For now we’ll gloss over them a little at least until we explore Castle Active Record.

The views and controllers have a linked structure as each controller has a corresponding folder under the views folder. These individual view folders then contain a .vm file for each action that can be performed on the controller. These .vm files are the NVelocity templates and contain our presentation only, including some lightweight presentation logic to loop over collections or other presentation specific operations.

Now, looking at the controllers folder we have 3 controllers listed (Contact, Home and Login) along with BaseController. If we look further we can see that each of the 3 controllers inherits from BaseController, which in turn inherits from SmartDispatcherController. In Monorail, a controller is a class that inherits from Controller but usually you will use the SmartDispatcherController as this provides us with some very powerful data binding capabilities.

A closer look at a controller

OK, so let’s crack open one of our starting controllers and see what we can find. Since we are on the home/index.castle page then let’s pick on the HomeController as this is the one that maps to our current page.

Looking inside HomeController we have 2 public methods called Index and BlowItAway. Both are actions on the controller and our current page of home/index.castle maps to the Index method.

Within the Index method we see an assignment to PropertyBag. The PropertyBag is one of a couple of ways of passing information over to a view from the controller. By assigning DateTime.Now to PropertyBag[“AccessDate”] we are giving the view the current time via a view variable of “AccessDate”. If we open up the Views/Home/Index.vm file we can use this variable. Find the <div id=”greeting”> line and add the following new div below it:

<div>The time is $AccessDate</div>

Save the Index.vm file and refresh your browser. You should now see the date and time output. At the moment it doesn’t look very pretty but notice how we’ve output a dynamic variable without jumping through the usual ASP.NET escaping into server code in the page. Our usual way of doing this would be something like <div>The time is <%= DateTime.Now %></div>.

Not only that, but we haven’t embedded the logic of using DateTime.Now within the page itself. The controller is where we decide this type of logic and the view itself remains very light. In my mind this is one of the big benefits of using Monorail, it is naturally guiding us to separate our logic from our views. This is possible with web forms but it’s something we have to enforce ourselves and it is very easy to slip back into bad habits (well, it is for me anyway).

But now lets fix the ugly nature of our date time format. Change the view code to <div>The time is $AccessDate.ToString(‘HH:mm’)</div>. Now we get just the time output. NVelocity is dynamically calling the ToString for us.

But have we just mixed logic that the controller should be handling for us? That depends. If it’s something that needs to be enforced and testable then keep the view light and just output $AccessDate and change the controller to push the correctly formatted time into the property bag.

OK – this wraps it up for our explore of the starting application for now. For our next post we’ll add a new controller and wire it up with Windsor.

I’m planning on this being a start of a series of posts on Monorail, the MVC web framework from the Castle Project ( So, how to get started with Castle Monorail.

The first starting point is to download the last full release which is 1.0 Release Candidate 3. This is the first potential stumbling block for many in that it is a release candidate rather than a full release and has remained in this state since September 2007. However, the whole castle stack is, from my experience, very stable with a whole array of tests and is actively being developed.

Once downloaded, install and you should now have all the binaries etc located under C:\Program Files\CastleProject. This includes the Visual Studio integration to provide a Monorail and Active Record project types to get you started (although only available for VS2005 at this point in time).

Now, fire up VS2005 and create a new project. Select Visual C#->Castle Monorail Project. This will start up the Monorail project wizard.

Castle VS Wizard 1st Screen

For an initial getting started we’ll stick with the NVelocity view engine but we’ll enable Windsor integration as we’ll lean on this in a following post. We’ll also ignore the routing engine for two reasons. For one, we don’t really need it right now, and the other more important reason is that it causes an error with the end project. OK, next screen.

Castle VS Wizard 2nd Screen

For now, we’ll ignore these options but we’ll come back to the Active Record Integration in a later post.

Castle VS Wizard Last Screen

The last wizard screen asks us if we are a TDD enthusiast and if selected gives us a separate test project using NUnit as the test framework. Keep this option selected and hit Finish.

We now have our starting Monorail project. To see it in action select the properties of the project and set the web properties to use either IIS or the VS Development Server and hit F5.

Monorail Starting Application 

You should get the homepage as above. This is the starting Monorail application generated by the wizard and gives us everything we need for starting out with Monorail and the ending point for this blog post. Further posts will explore the different elements of Monorail, its testability and the Windsor integration.

I’ve had an interest in the Castle stack for a while now but I haven’t yet had a chance to use Monorail in anger. At my current contract we have been having some nice healthy discussions about development in general (principles, Microsoft’s involvement in OSS, MVC) and I’ve mentioned Monorail several times. This has happened so frequently now that I’ve managed to infect at least one person here to look into more at the weekend and at the same time I’ve now become infected as well.

I’ve been playing around with it a bit in the evenings and it feels so refreshing. Moving away from web forms is like a breath of fresh air. I’ve read about this reaction on several blogs so I knew I would feel the same but I didn’t realise just how much more free I would feel. It really is like a heavy burden being lifted from your shoulders.

Now, it is very early days but I intend to delve deeper into Monorail along with the integration with the rest of the Castle stack and will be planning on posting updates on my travels. The main stumbling block I always have is having that meaty project to base it all around. I have a plan for that so we’ll see how it goes.