ASP.NET MVC with Windsor – programmatic controller registration

March 28, 2009 at 11:29 AMAndre Loker

Although I’m a loyal MonoRail user, I’m playing with ASP.NET MVC a bit sometimes if time permits. One of the first things I wanted to do is using an IoC container such as Windsor to resolve controllers. ASP.NET MVC was built with extensibility in mind, so that’s not much of a problem, and it has been written about, for example by Matt Hall.

The problem is that the articles I read use the Windsor XML configuration for this. Frankly, I don’t like to configure my IoC container using XML if I don’t have to. Its syntax is pretty verbose and honestly I don’t need the controllers to be configured externally. Therefore, I prefer to use programmatic registration. Windsor has such a sweet registration API, you got to love it.

Alright, so what do you have to do to make programmatically registered controllers available to ASP.NET MVC?

Step 1 – create the container instance

This is easy: in the Application_Start event create the WindsorContainer and store it in a static(!) field. It has to be static, because more than one instance of the HttpApplication can potentially be created.


   1: public class MvcApplication : System.Web.HttpApplication {
   2:   static IWindsorContainer container;
   4:   protected void Application_Start() {
   5:     CreateWindsorContainer();
   6:     RegisterRoutes(RouteTable.Routes); // has been there before!
   7:   }
   9:   static void CreateWindsorContainer() {
  10:     container = new WindsorContainer();
  11:   }
  12: }

Did I mention that the container field needs to be static?

Step 2 – register controllers

This is where the nice API of Windsor comes into play. Extend the application as follows:

   1: public class MvcApplication : System.Web.HttpApplication{
   2:   ...
   4:   protected void Application_Start() {
   5:     CreateWindsorContainer();
   6:     RegisterRoutes(RouteTable.Routes);
   7:     RegisterControllers(); // added
   8:   }
  10:   ...
  12:   static void RegisterControllers() {
  13:     container.Register(
  14:       AllTypes
  15:         .FromAssembly(Assembly.GetExecutingAssembly())
  16:         .BasedOn<IController>()        
  17:     );
  18:   }
  19: }

This is simple, isn’t it? No per-controller-entry in some XML file, just a simple piece of code.

Step 3 – create your own controller factory

To create the controller instances, ASP.NET MVC uses an object that implement IControllerFactory. So all we need to do is roll our own controller factory that uses Windsor and tell ASP.NET MVC to use that.

OK, so here’s our controller factory:

   1: public class WindsorControllerFactory : IControllerFactory {
   3:   readonly IWindsorContainer container;
   5:   public WindsorControllerFactory(IWindsorContainer container) {
   6:     this.container = container;
   7:   }
   9:   public IController CreateController(RequestContext requestContext, string controllerName) {
  10:     var componentName = GetComponentNameFromControllerName(controllerName);
  11:     return container.Resolve<IController>(componentName);
  12:   }
  14:   public void ReleaseController(IController controller) {
  15:     container.Release(controller);
  16:   }
  18:   /// <summary>
  19:   /// Maps from a simple controller name to the name of the component
  20:   /// that implements the controller.
  21:   /// </summary>
  22:   /// <param name="controllerName">Name of the controller.</param>
  23:   /// <returns>Name of the controller component.</returns>
  24:   static string GetComponentNameFromControllerName(string controllerName) {
  25:     var controllerNamespace = typeof(HomeController).Namespace;
  26:     return string.Format("{0}.{1}Controller", controllerNamespace, controllerName);
  27:   }
  28: }

Nothing fancy here: first, we’ll need the windsor container instance, so we pass it as a constructor dependency. CreateController and ReleaseController are the two methods of IControllerFactory – their purpose should be self-explanatory. GetComponentNameFromControllerName maybe needs some further explanation. ASP.NET MVC will ask for controllers by their simple name, that is “Home” or “About” etc. However, by the way we registered the controller components Windsor knows them by their full type name, e.g. “MyApplication.Controllers.HomeController” and “MyApplication.Controllers.AboutController”. GetComponentNameFromControllerName simply converts from the simple controller name to the full component name.

Step 4 – tell ASP.NET MVC to use our controller factory

The last step is to tell ASP.NET MVC to actually use our IControllerFactory implementation instead of the default one. Conceptually this is easy, we only need to call ControllerBuilder.Current.SetControllerFactory and pass it either the type of our IControllerFactory implementation or an instance. But let’s not be too quick here and try to keep our application as DI-ish as possible. Here’s how I’d set the controller factory:

   1: public class MvcApplication : System.Web.HttpApplication{
   2:   ...
   4:   protected void Application_Start() {
   5:     CreateWindsorContainer();
   6:     RegisterRoutes(RouteTable.Routes);
   7:     RegisterControllers();
   8:     RegisterControllerFactory(); // new
   9:   }
  11:   void RegisterControllerFactory() {
  12:     container.Register(
  13:       Component
  14:         .For<IControllerFactory>()
  15:         .ImplementedBy<WindsorControllerFactory>()
  16:         .LifeStyle.Singleton
  17:       );
  18:     var controllerFactory = container.Resolve<IControllerFactory>();
  19:     ControllerBuilder.Current.SetControllerFactory(controllerFactory);
  20:   }
  22:   static void CreateWindsorContainer() {
  23:     container = new WindsorContainer();
  24:     // new: register the container with itself 
  25:     //      to be able to resolve the dependency in the ctor
  26:     //      of WindsorControllerFactory
  27:     container.Register(
  28:       Component
  29:         .For<IWindsorContainer>()
  30:         .Instance(container)
  31:       );
  32:   }  
  34:   ...
  35: }

You see, instead of new-ing an instance of WIndsorControllerFactory we register it as a singleton component and resolve it. Also note that we needed to register the Windsor container with itself to have the constructor dependency resolved.

Finally, here’s the complete source code of the global application class so far:

   1: public class MvcApplication : System.Web.HttpApplication {
   2:   static IWindsorContainer container;
   4:   public static void RegisterRoutes(RouteCollection routes) {
   5:     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   7:     routes.MapRoute(
   8:       "Default", // Route name
   9:       "{controller}/{action}/{id}", // URL with parameters
  10:       new { controller = "Home", action = "Index", id = "" } // Parameter defaults
  11:       );
  12:   }
  14:   protected void Application_Start() {
  15:     CreateWindsorContainer();
  16:     RegisterRoutes(RouteTable.Routes);
  17:     RegisterControllers();
  18:     RegisterControllerFactory();
  19:   }
  21:   static void CreateWindsorContainer() {
  22:     container = new WindsorContainer();
  23:     container.Register(
  24:       Component
  25:         .For<IWindsorContainer>()
  26:         .Instance(container)
  27:       );
  28:   }
  30:   static void RegisterControllers() {
  31:     container.Register(
  32:       AllTypes
  33:         .FromAssembly(Assembly.GetExecutingAssembly())
  34:         .BasedOn<IController>()
  35:       );
  36:   }
  38:   static void RegisterControllerFactory() {
  39:     container.Register(
  40:       Component
  41:         .For<IControllerFactory>()
  42:         .ImplementedBy<WindsorControllerFactory>()
  43:         .LifeStyle.Singleton
  44:       );
  45:     var controllerFactory = container.Resolve<IControllerFactory>();
  46:     ControllerBuilder.Current.SetControllerFactory(controllerFactory);
  47:   }
  48: }

Controller names and component names revisited

As you saw in step 3, we need to map the controller names to component names. This doesn’t take much effort and is my preferred way of handling this. But of course, you can already register the controller components with the respective controller names in the first place if you like. Just change the controller registration to something like this:

   1: static void RegisterControllers() {
   2:   container.Register(
   3:     AllTypes
   4:       .FromAssembly(Assembly.GetExecutingAssembly())
   5:       .BasedOn<IController>()
   6:       // modify the name with which the component is registered:
   7:       .Configure(component => component.Named(ControllerNameFromType(component.Implementation)))
   8:     );
   9: }
  11: static string ControllerNameFromType(Type implementation) {
  12:   const string ControllerSuffix = "Controller";
  13:   var name = implementation.Name;
  14:   Debug.Assert(name.EndsWith(ControllerSuffix));
  15:   return name.Substring(0, name.Length - ControllerSuffix.Length);
  16: }

If you do this, you can remove the GetComponentNameFromControllerName method and simplify the implementation of IControllerFactory.CreateController to this:

   1: public IController CreateController(RequestContext requestContext, 
   2:                                     string controllerName) {
   3:   return container.Resolve<IController>(controllerName);
   4: }

Which version you choose is more or less a matter of taste. If you keep the full type name as the component’s name you reduce the chance for name clashes. However, if you register the components using the controller name creating the controller is slightly simpler.

More simplifications

You can even simplify the controller factory a bit if you inherit from DefaultControllerFactory instead of implementing IControllerFactory. Because DefaultControllerFactory will resolve the correct component type for you, you can simply override GetControllerInstance instead of implementing CreateController:

   1: public class WindsorControllerFactory : DefaultControllerFactory {
   2:   readonly IWindsorContainer container;
   4:   public WindsorControllerFactory(IWindsorContainer container) {
   5:     this.container = container;
   6:   }
   8:   protected override IController GetControllerInstance(System.Type controllerType) {
   9:     return container.Resolve(controllerType) as IController;
  10:   }
  12:   public override void ReleaseController(IController controller) {
  13:     container.Release(controller);
  14:   }
  15: }

If you need to change the way that the controller name is mapped to a component type, you can also override GetControllerType.

MVC Contrib

As far as I know Windsor integration is also part of the MVC Contrib project. I haven’t looked into it, so bear with me if this article doubles existing code!

Posted in: ASP.NET | Castle

Tags: , , ,

Re: Health Monitoring in ASP.NET 3.5

March 12, 2009 at 11:33 AMAndre Loker

Some days ago, I read this cool article about the built in health monitoring features of ASP.NET. Funny that I never stumbled across that - I always implemented my own health monitoring.

The other day I played around with the health monitoring feature and it looks really great. As a quick reference here’s a short description of the elements of the health monitoring facility:



This element describes which events are to be captured. The type attribute references one of the event types derived from WebBaseEvent. All events of that type or a derived type are captured. For example, to capture all kinds of errors in the application, type would be set to System.Web.Management.WebBaseErrorEvent, for events regarding the application lifecycle (start, restart, stop etc.) one would use System.Web.Management..WebApplicationLifetimeEvent. You can further filter on a specific range of error codes (e.g. as defined in the WebEventCodes class).

The machine wide web.config has already defined numerous event mappings for you, so it’s unlikely that you need to define your own:

  • All Events, captures all events (WebBaseEvent and below)
  • Heartbeats, captures events that are automatically generated by ASP.NET in a given interval as defined by the heartbeatInterval attribute of the healthMonitoring section (WebHeartbeatEvent)
  • Application Lifetime Events, captures compilation, application startup, restart, shutdown (WebApplicationLifetimeEvent)
  • Request Processing Events, raised on each and every request (WebRequestEvent)
  • All Errors, captures all errors (WebBaseErrorEvent and below)
    Infrastructure Errors, captures all system related errors (WebErrorEvent)
  • Request Processing Errors, captures all request related errors (WebRequestErrorEvent and below)
  • All Audits, captures security related events (WebAuditEvent)
  • Failure Audits, captures failed audits (WebFailureAuditEvent)
  • Success Audits, likewise captures succeeded audits (WebSuccessAuditEvent)

The bold part is the name of the event mapping.


Providers describe how to process an event. ASP.NET comes bundled with a good selection of providers that cover most needs, for example:

  • write to the event log: EventLogWebEventProvider
  • write to the ASP.NET trace: TraceWebEventProvider
  • send an email when the event is captured: SimpleMailWebEventProvider and TemplatedMailWebEventProvider
  • write to a sql server table: SqlWebEventProvider

Again, ASP.NET has some standard providers defined:

  • EventLogProvider, writes to the event log
  • SqlWebEventProvider, writes to a database using the connection string named LocalSqlServer
  • WmiWebEventProvider, generates WMI events

As you see, you’ll have to setup a mail sending provider yourself, but this is shown in the article mentioned above.


EventMappings and Providers won’t do you any good unless you define a rule. It’s the rules that actually activate the health monitoring system: they link providers and event mappings. Use the “eventName” attribute define the set of events to be captured and the “provider” attribute to decide what to do with those events.

You can configure additional settings, like

  • how often has an event to be raised before the provider performs its action (minInstances)
  • how often may events occur before processing is stopped (maxLimit), may have the value “Infinite” or an integer
  • what is the interval within which consecutive occurrences of an event are ignored (minInterval)

Instead of defining the settings above with each and every rule you can – and should - use profiles instead (see below).

As with the other elements there are two prefab rules, both of which use the EventLogProvider to write events to the Windows event log:

  • All Errors Default, logs “All Errors” at a minInteval of 1 minute
  • Failure Audits Default, logs "Failure Audits" also at a minInterval of 1 minute


As mentioned above, profiles are used to centralize the configuration of the settings minInstances, maxLimit and minInterval. Simple define a profile, name it and use this name as the value of a rule’s “profile” element. Nothing fancy, but useful.

Two profiles are defined in the global web.config:

  • Default: minInstances = 1, maxLimit = Infinite, minInterval = 1 minute (00:01:00)
  • Critical: minInstances = 1, maxLimit = Infinite, minInterval = 0 seconds (00:00:00), that is each occurrence will be processed


Finally, we have the buffer modes. If you enable buffering on a provider (buffer=”true”) you also need to define how the buffering is done by referencing a specific buffer mode (bufferMode=”name of a buffer mode”). According to the documentation, buffer modes only apply to the SQLWebEventProvider, but I haven’t checked that.

The global web.config defines four buffer modes, ranging from least aggressive buffering for critical events to large buffers for non-crucial events:

  • Critical Notification
  • Notification
  • Analysis
  • Logging

For details of the configured values, look at your global web.config or at the documentation.

MSDN links:

Posted in: ASP.NET

Tags: ,

Upgrading BlogEngine.NET from 1.4 to 1.4.5.x

September 3, 2008 at 8:31 PMAndre Loker

About two month ago I wrote about small issues I faced when I upgraded from BlogEngine.NET 1.3.1 to version 1.4. Today I updated my blog software again, this time to the trunk version of BlogEngine.NET. Almost everything went smoothly there were a few glitches I had to fix before I was satisfied with the results.

Here are the most important points: 

  • First of all, the issues with the strange author name in the RSS feed ( has been taken care of in version Nice! Note that the official 1.4.5 release from august 1st does not yet fix the issue. You'll need a revision 16044 or higher.
  • The strange e-mail fields (second point in my first post) are not really fixed - as far as "fixed" is the correct term - according to Mads Kristensen this was attentional. Mads has changed the behaviour a bit, however to the worse if you ask me. As mentioned in my first post if someone contacts you with the contact form you'd get an e-mail with your name and your email address as the "From" field. "Sender" and "Reply-To" headers are added which include the author's name and e-mail address. I mentioned some issues that are caused by this, for example that Thunderbird uses the "From" field when quoting a mail ("Andre Loker wrote:")
    Now it has changed slightly: the "From" field contains the name of the mail's author but the e-mail address of your blog. While this fixes the issue when quoting the mail it causes a worse issue: if you try to add the author to your address book, chances are that your mail application uses the author's name but your e-mail address. I created an issue for this bug - at least I think it should be considered a bug.
    To sanitize the situation I modified the code to create one reasonable "from" header and don't add any further headers to the mail:
       1: // Contact.aspx.cs - replace this:
       2: mail.From = new MailAddress(BlogSettings.Instance.Email, name);
       3: mail.ReplyTo = new MailAddress(email, name);
       4: mail.Sender = mail.ReplyTo;
       6: // with:
       7: mail.From = new MailAddress(email, name);
  • The current version of the contact form behaves a bit odd or doesn't work at all if attachments are disabled in the contact form, as it is in my blog. The issue is known, so we can expect a fix in the future. As a preliminary fix you can change contact.aspx like this:
       1: // line 48ff:
       2: // replace:
       3: if ($('<%=txtAttachment.ClientID%>').value.length > 0)
       4:   return true;
       6: //with
       7: <% if(BlogSettings.Instance.EnableContactAttachments) {%>
       8: if ($('<%=txtAttachment.ClientID%>').value.length > 0)
       9:   return true;
      10: <%}%>

Aside from these issues the people behind BlogEngine.NET have done a great task to improve their product.  I wholeheartedly recommend it to anyone asking for .NET based blogging software.

Posted in: ASP.NET | Meta

Tags: ,


June 27, 2008 at 5:01 PMAndre Loker

HTTP methods

As you probably know, HTTP supports several methods that define the nature of the current request. The two most important ones are GET and POST. GET is the primary method to get content (so called entities) from the server such as  HTML pages, images, CSS style sheets etc. The POST method on the other hand is meant to transport entities to the server, for example login credentials or a blog comment. On the server side a POST request often results in an update of certain data (databases, session state).

Both GET and POST can return an entity as a response. For GET this is obvious - it's what the method exists for in the first place. For POST it might sound reasonable in the first place as well, but it brings a pile of problems.

A simple scenario

Imagine you fill in a sign-up form of some web based e-mail service and POST it to the server using a submit button. The server processes the new account and updates its database. Maybe it even logs you in directly. In response of the POST request the server directly shows you a view of your inbox. Here's a diagram of what happens between browser and server:


  1. The browser POSTs form data to an URL called signup.aspx
  2. The server processes the request
  3. The server responds with a status code of 200 (OK) and sends back a view of the new users inbox rendered as HTML

You leave the computer to have a coffee and when you come back 5 minutes later you refresh the page (using CTRL+R or F5 or whatever shortcut your browser uses) to see whether you already have new messages. You are a bit puzzled why this (or a similar) message box appears:


You click on OK and are even more confused as the page that appears says "This user name is already taken" instead of showing your inbox .

What has happened? Remember that the page you saw was the response of a POST request (submitting the sign up form). When you refreshed the page and confirmed to "resend the data" you actually repeated the POST request with the same form data. The server processed the "new" account and found that the user name is already in use (by yourself!), therefore it showed an error. "But wait", you say, "I just wanted the server to refresh the view of my inbox, what have I done wrong? " The answer is: nothing! The problem is that the application abused the POST response to transport an entity back to the client that should have been accessed with a GET request in the first place.

POST related issues

Here are some of the problems that occur if you abuse POST requests to return entities:

1. Refreshing the page results in a re-transmission of the POST data

This is what I described above. Hitting "refresh page" for a reponse based on a POST request will re-issue the POST request. Instead of refreshing what you see this will repeat what you did to reach the current page. This is not "refresh page" anymore, it becomes "repeat last action" - which is most likely not what the user wants. If you see a summary page after you have submitted an order in an online store, you don't want F5 to drop another order, do you?

2. POST responses are hard to bookmark

Bookmarks (or favourites etc.) normally only remember the URL of the bookmarked page (along with some user supplied meta data). Because a POST request transports data in the request body instead as query parameters in the URL like GET does, bookmarking the result of a POST will not work in most cases.

3. POST responses pollute the browser history

If the browser keeps the result of a POST request in it's history, going back to that history entry will normally result in POST data to be retransmitted. This again causes the same issues as mentioned in point 1.


"But I need POSTs to send forms to the server - how can I avoid the problems mentioned above?" you might say. Here's where the POST-Redirect-GET (PRG hereafter) pattern enters the stage.

Instead of sending entity content with the POST response after we processed the request, we return the URL of a new location which the browser should visit afterwards. Normally this new location shows the result of the POST or an updated view of some domain model.

This can be achieved by not returning a result code of 200 (success) but instead returning a status code that indicates a new location for the result, for example 303 ("See other") or 302("Found"/"Moved temporarily"), the latter of which is used most often nowadays. Together with the 30x result code a Location header is sent which contains the URL of the page to which the request is redirected. Only the headers are sent, no body is included.

If the browser sees the 30x status code, it will look for the Location header and issue a GET request to the URL mentioned there. Finally the user will see the body of that GET request in the browser.

The browser-server communication would look like this:


  1. The browser POSTs to signup.aspx
  2. The server updates some state etc.
  3. The response is 302 redirect with a Location header value of inbox.aspx
  4. The browser realizes that the response is redirected and issues a GET to inbox.aspx
  5. The server returns 200 together with the content of the resource.

What do we gain?

  • The page can be safely refreshed. Refreshing will cause another GET to inbox.aspx which won't cause any updates on the server
  • The result page can be easily bookmarked. Because the current resource is defined by the URL a bookmark to this URL is likely to be valid.
  • The browser history stays clean. Responses that have a redirect status code (such as 302) will not be put into the browser cache by most browsers. Only the location to which the response is redirecting is. Therefore signup.aspx won't be added to the history and we can safely go back and forth through the history without having to resubmit any POST data

The drawbacks of POST-Redirect-GET

While it should be clear by now that the POST-Redirect-GET pattern is the way to go in most situations, I'd like to point at the few drawbacks that come along with this pattern.

First of all, redirection from one request to another causes an extra roundtrip to the server (one for the POST request, one for the GET request it redirects to). In this context the roundtrip should be understood as all processing and transmission time that is required and fixed per request, ie. transmission delay, creation and invation of the HTTP handler, opening and closing database connections/transactions, filling ORM caches etc.

If both requests can be handled very quickly by the server this will essentially double the response time. If your roundtrip time is 200ms, using PRG will cause a minimum delay of 400ms between submitting the form and the result page being visible. This issues has to be put in perspective with reality, however. The server will need some time processing both requests, so the percentage of time needed for the roundtrips decreases with the amount of time server processing time takes. The response from the POST itself can be extremely small (few hundred bytes), because only the headers need to be transmitted.

In practice I haven't noticed a real performance problem with PRG. A slow app will stay slow, a fast one won't truly suffer from the extra roundtrip. And besides, if you replace POSTs by GETs where appropriate the effect of PRG will be even less noticeable.

The problem with ASP.NET WebForms

Now that you know about POST-Redirect-GET you are of course eager to use it (at least I hope I could convince you). But as an ASP.NET WebForms developer you will soon run into problems: ASP.NET WebForms is fundamentally based on POSTs to the server. In essence, all ASP.NET web pages are wrapped in one huge <form> element with "method" set to "POST". Whenever you click a button, you essentially POST all form fields to the server. Of course you can redirect from a Button.Click handler. If you do so, you're applying PRG. At the same time you're working quite against the WebForms philosophy, especially the ViewState (which will get lost as soon as you redirect), which will force you to rethink a lot of your application logic. And if you don't rely on all this postback behaviour inherent to ASP.NET WebForms you might as well ask why you're using WebForms in the first place.

This makes clear why a lot of developers (including me) think that WebForms are inherently "broken" (viewstate, ubiquitous postbacks and the hard-to-mock HttpContext are just a few reasons). If you share these concerns but like .NET just as I do, you might want to look at alternate .NET based web frameworks such as Castle MonoRail or ASP.NET MVC.


In situations where you use AJAX the whole PRG issue becomes a new story. AJAX responses don't appear in the history, you wouldn't want to bookmark them and refreshing a web page does not re-issue any AJAX requests (except those fired on page load). Therefore I have no problem with returning entitiest (HTML fragments, JSON, XML) from AJAX POSTs - PRG is not of much use here.


To conclude this article here's a list of some basic rules that have been useful to me:

  1. Use POST-Redirect-GET whenever you can, that is: whenever you process a POST request on the server, send a redirect to a GETtable resource as response. It's applicable in almost all cases and will make your site much more usable for the visitor
  2. Don't POST what you can GET. If you only want to retrieve a parameterised resource it might be completely suitable to use a GET request with query string parameters. Google is a good example. The start page contains a simple form with a single text field to enter the search terms. Submitting the form causes a GET to /search with the search terms passed as the query string parameter q. This can be easily done by providing method="GET" on the <form> element (or just leave out the method attribute, as GET is the default).
  3. POST requests from AJAX are allowed to return entities directly as they don't suffer from the problems like "full" POSTs.

Posted in: ASP.NET | Patterns

Tags: , , ,

Speed up Firefox when using Development Server

June 18, 2008 at 1:17 PMAndre Loker

The problem

Using Firefox on Vista to view websites hosted by the Visual Studio Development Server can be unbearably slow. Pages take aeons (i.e. several seconds) to load while viewing the same site under IE does not suffer from this issue.

The solution

As mentioned in this blog post, this problem can be solved like this:

  1. Open the Firefox config (browse to about:config)
  2. Locate the setting: network.dns.disableIPv6 (type "v6" into the filter field)
  3. Change the value to true (double click the row)

The result

Now sites on the built in development server work fast even under Firefox and Vista.

The conclusion

What can I say - it works :-)

Update 06/19/2008: works with Firefox 3 as well

Posted in: ASP.NET

Tags: ,