# Sunday, December 20, 2009

I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection at Microsoft Denmark January 20th 2010.

The talk will be in Danish. Details and sign-up here.

posted on Sunday, December 20, 2009 8:56:33 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, December 14, 2009

In my previous posts I discussed how to enable global error handling in ASP.NET MVC and how to inject a logging interface into the error handler. In these posts, I simplified things a bit to get my points across.

In production we don't use a custom ErrorHandlingControllerFactory to configure all Controllers with error handling, nor do we instantiate IExceptionFilters manually. What I described was the Poor Man's Dependency Injection (DI) approach, which I find most appropriate when describing DI concepts.

However, we really use Castle Windsor currently, so the wiring looks a bit different although it's still exactly the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter are any different than I have already described, but for completeness I wanted to share a bit of our Windsor code.

This is how we really wire our Controllers:

container.Register(AllTypes
    .FromAssemblyContaining(representativeControllerType)
    .BasedOn<Controller>()
    .ConfigureFor<Controller>(reg => 
        reg.LifeStyle.PerWebRequest.ServiceOverrides(
            new { ActionInvoker = typeof(
                ErrorHandlingControllerActionInvoker)
                .FullName })));

Most of this statement simply instructs Windsor to scan all types in the specified assembly for Controller implementations and register them. The interesting part is the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining that the ActionInvoker property should be wired up with an instance of the component registered as ErrorHandlingControllerActionInvoker.

Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance we need to configure at least one of these as well. Instead of one, however, we have two:

container.Register(Component.For<IExceptionFilter>()
    .ImplementedBy<LoggingExceptionFilter>());
container.Register(Component.For<IExceptionFilter>()
    .ImplementedBy<HandleErrorAttribute>());

This is Windsor's elegant way of registering Decorators: you simply register the Decorator before the decorated type, and it'll Auto-Wire everything for you.

Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from the MVC Contrib project.

To reiterate: You don't have to use Castle Windsor to enable global error handling or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous posts, or you can use some other DI Container. The purpose of this post was simply to demonstrate one way to take it to the next level.

posted on Monday, December 14, 2009 7:59:32 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Monday, December 07, 2009

In a previous post I described how to enable global error handling in ASP.NET MVC applications. Although I spent some time talking about the importance of DRY, another major motivation for me was to enable Dependency Injection (DI) with exception handling so that I could log stack traces before letting ASP.NET MVC handle the exception.

With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter implementation. As an example I used HandleErrorAttribute, but obviously that doesn't log anything. Once again, it would be tempting to derive from HandleErrorAttribute and override its OnException method, but staying true to the Single Responsibility Principle as well as the Open/Closed Principle I rather prefer a Decorator:

public class LoggingExceptionFilter : IExceptionFilter
{
    private readonly IExceptionFilter filter;
    private readonly ILogWriter logWriter;
 
    public LoggingExceptionFilter(IExceptionFilter filter,
        ILogWriter logWriter)
    {
        if (filter == null)
        {
            throw new ArgumentNullException("filter");
        }
        if (logWriter == null)
        {
            throw new ArgumentNullException("logWriter");
        }        
 
        this.filter = filter;
        this.logWriter = logWriter;
    }
 
    #region IExceptionFilter Members
 
    public void OnException(ExceptionContext filterContext)
    {
        this.logWriter.WriteError(filterContext.Exception);
        this.filter.OnException(filterContext);
    }
 
    #endregion
}

The LoggingExceptionFilter shown above is unabridged production code. This is all it takes to bridge the gap between IExceptionFilter and some ILogWriter interface (replace with the logging framework of your choice). Notice how it simply logs the error and then passes on exception handling to the decorated IExceptionFilter.

Currently we use HandleErrorAttribute as the decorated filter so that behavior stays as expected.

c.ActionInvoker = 
    new ErrorHandlingControllerActionInvoker(
        new LoggingExceptionFilter(
            new HandleErrorAttribute(), logWriter));

This is not too different from before, except that a LoggingExceptionFilter now decorates the HandleErrorAttribute instance.

posted on Monday, December 07, 2009 7:20:27 AM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, December 05, 2009

A reader asked me how AutoFixture can deal with arrays as fields on a class. More specifically, given a class like MyClassA, how can AutoFixture assign a proper array with initialized values to Items?

public class MyClassA
{
    public MyClassB[] Items;
    public MyClassC C;
    public MyClassD D;
}

Ignoring the bad practice of publicly exposing fields, the main problem is that AutoFixture has no inherent understanding of arrays, so if we try to create a new instance of MyClassA by invoking the CreateAnonymous method, we would end up with Items being an array of nulls.

Obviously we want a populated array instead. There are at least a couple of ways to reach this goal.

The simplest is just to create it and modify it afterwards:

var mc = fixture.CreateAnonymous<MyClassA>();
mc.Items = fixture.CreateMany<MyClassB>().ToArray();

Although the CreateAnomymous method will assign an unitialized array, we immediately overwrite the value with an initialized array. The CreateMany method returns an IEnumerable<MyClassB> on which we can use the ToArray extension method to create an array.

The next option is to do almost the same thing, but as a single operation:

var mc = fixture.Build<MyClassA>()
    .With(x => x.Items, 
        fixture.CreateMany<MyClassB>().ToArray())
    .CreateAnonymous();

Besides the different syntax and the lower semicolon count, the biggest difference is that in this case the Items field is never assigned an unitialized array because the With method ensures that the specified value is assigned immediately.

If you get tired of writing this Builder sequence every time you want to create a new MyClassA instance, you can Customize the Fixture:

fixture.Customize<MyClassA>(ob =>
    ob.With(x => x.Items, 
        fixture.CreateMany<MyClassB>().ToArray()));

With this customization, every time we invoke

var mc = fixture.CreateAnonymous<MyClassA>();

we will get an instance of MyClassA with a properly initialized Items array.

I hope you find one or more of these methods useful.

posted on Saturday, December 05, 2009 1:41:45 AM (Romance Standard Time, UTC+01:00)  #    Comments [1] Trackback
# Tuesday, December 01, 2009

ASP.NET MVC comes with an error-handling feature that enables you to show nice error Views to your users instead of the dreaded Yellow Screen of Death. The most prominently described technique involves attributing either you Controller or a single Controller action, like we see in the AccountController created by the Visual Studio project template.

[HandleError]

public class AccountController : Controller { }

That sure is easy, but I don't like it for a number of reasons:

  • Even though you can derive from HandleErrorAttribute, it's impossible to inject any dependencies into Attributes because they must be fully constructed at compile-time. That makes it really difficult to log errors to an interface.
  • It violates the DRY principle. Although it can be applied at the Controller level, I still must remember to attribute all of my Controllers with the HandleErrorAttribute.

Another approach is to override Controller.OnException. That solves the DI problem, but not the DRY problem.

Attentive readers may now point out that I can define a base Controller that implements the proper error handling, and require that all my Controllers derive from this base Controller, but that doesn't satisfy me:

First of all, it still violates the DRY principle. Whether I have to remember to apply a [HandleError] attribute or derive from a : MyBaseController amounts to the same thing. I (and all my team members) have to remember this always. It's unnecessary project friction.

The second thing that bugs me about this approach is that I really do favor composition over inheritance. Error handling is a cross-cutting concern, so why should all my Controllers have to derive from a base controller to enable this? That is absurd.

Fortunately, ASP.NET MVC offers a third way.

The key lies in the Controller base class and how it deals with IExceptionFilters (which HandleErrorAttribute implements). When a Controller action is invoked, this actually happens through an IActionInvoker. The default ControllerActionInvoker is responsible for gathering the list of IExceptionFilters, so the first thing we can do is to derive from that and override its GetFilters method:

public class ErrorHandlingActionInvoker :

    ControllerActionInvoker

{

    private readonly IExceptionFilter filter;

 

    public ErrorHandlingActionInvoker(

        IExceptionFilter filter)

    {

        if (filter == null)

        {

            throw new ArgumentNullException("filter");

        }

 

        this.filter = filter;

    }

 

    protected override FilterInfo GetFilters(

        ControllerContext controllerContext,

        ActionDescriptor actionDescriptor)

    {

        var filterInfo =

            base.GetFilters(controllerContext,

            actionDescriptor);

        filterInfo.ExceptionFilters.Add(this.filter);

        return filterInfo;

    }

}

Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not tightly binding it to any particular implementation – it will work with any IExceptionFilter we give it, so it simply serves the purpose of adding the filter at the right stage so that it can deal with otherwise unhandled exceptions. It's pure infrastructure code.

Notice that I first invoke base.GetFilters and then add the injected filter to the returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to attempt to deal with the error first.

This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every Controller in the application. This can be done using a custom ControllerFactory:

public class ErrorHandlingControllerFactory :

    DefaultControllerFactory

{

    public override IController CreateController(

        RequestContext requestContext,

        string controllerName)

    {

        var controller =

            base.CreateController(requestContext,

            controllerName);

 

        var c = controller as Controller;

        if (c != null)

        {

            c.ActionInvoker =

                new ErrorHandlingActionInvoker(

                    new HandleErrorAttribute());

        }

 

        return controller;

    }

}

Notice that I'm simply deriving from the DefaultControllerFactory and overriding the CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.

In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker instance. This seems weird, but it's the HandleErrorAttribute that implements the default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter, it works like a charm.

The only thing left to do is to wire up the custom ErrorHandlingControllerFactory in global.asax like this:

ControllerBuilder.Current.SetControllerFactory(

    new ErrorHandlingControllerFactory());

Now any Controller action that throws an exception is gracefully handled by the injected IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters, any normal [HandleError] attribute and Controller.OnException override gets a chance to deal with the exception first, so this doesn't even change behavior of existing code.

If you are trying this out on your own development machine, remember that you must modify your web.config like so:

<customErrors mode="On" />

If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on your local box.

posted on Tuesday, December 01, 2009 7:37:01 AM (Romance Standard Time, UTC+01:00)  #    Comments [6] Trackback