Rickard Nilsson

  • Blog
  • Archive
  • About
  • Contact

Welcome to rickardnilsson.net

Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More

Rickard blogs about crafting software using .NET tooling and solid, development practices.

Follow @rickardn

Top Posts

  • Applying stylesheets dynamically with jQuery
  • My customized Son of Obsidian Visual Studio color scheme for ReSharper
  • .NET Development with Visual Studio on MacBook Pro
  • Code Kata Cast
  • ReSharper User tip #2: Refactor rename namespace
  • Combining and minifying JavaScript and CSS files with Ajax Minifier
  • Dependency injection in ASP.NET MVC with Unity IoC Container
  • C# REPL and Interactive interpreter

Categories

  • .NET
  • Agile
  • ASP.NET 2.0
  • ASP.NET 3.5
  • ASP.NET 4
  • ASP.NET MVC
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • C# 4.0
  • Continuous Integration
  • CSS
  • Design by Contract
  • Design Patterns
  • iPhone
  • JavaScript
  • Kata
  • Moles
  • Open source
  • Personal
  • Review
  • Social media
  • Software development
  • TDD
  • Testing
  • Umbraco
  • Unit testing
  • Unity
  • User tip
  • Web development

Five most recent posts

  • How to unit test your database code when using ServiceStack OrmLite
  • Extract class - ReSharper Ninja tricks
  • ASP.NET MVC 3 Template with built in JavaScript and CSS merging and minification
  • ReSharper Ninja tricks - Generate code from usage
  • Unit testing continuously

Tag cloud

  • agile
  • blogengine.net
  • c#
  • code kata
  • codegarden11
  • continuous integration
  • css
  • dependency injection
  • fakes
  • iso 8601
  • javascript
  • jquery
  • refactoring
  • resharper
  • resharper usertip
  • tdd
  • testing
  • umbraco
  • unit test
  • unit testing
  • visual studio

Recent comments

ASP.NET MVC 2 Framework and Unity 2.0 Dependency Injection Container

Sunday, 6 June 2010 23:30 by Rickard Nilsson

Update! Download sample project MvcWithUnity.VS2010.zip (727,52 kb)

This is an update to a previous post on MVC and Unity: Dependency injection in ASP.NET MVC with Unity IoC Container

After my previous post, new versions of both ASP.NET MVC and Unity has been released and some confusion about their compatibility has shown up on the Internet. The first hit on Google on the topic is this which is completely wrong and uninformed. BillKrat writes:

"MVC2 will pull the rug out from under these blogs because the IControllerFactory interface for CreateController no longer provides a "type" - it provides a "string" which will simply hold the controllerName; not as easy to work with."

In fact, this is not the case at all. The following snippet is fresh out of the code repository from the MVC 1.0 relase:

public interface IControllerFactory {
    IController CreateController(RequestContext requestContext, string controllerName);
    void ReleaseController(IController controller);
}

thus, the interface has not changed at all, and all samples on integrating ASP.NET MVC with Unity still apply!

What BillKrat has done is to mistake the interface for the base implementation in System.Web.Mvc.DefaultControllerFactory. If we subclass DefaultControllerFactorty all we need to do is this (as I’ve explained previously):

public class UnityControllerFactory : DefaultControllerFactory {
    private readonly IUnityContainer container;
    public UnityControllerFactory(IUnityContainer container) {
        this.container = container;
    }
    protected override IController GetControllerInstance(
                RequestContext requestContext, Type controllerType) { 
        return container.Resolve(controllerType) as IController; 
    }
}

thus, here we get our type which plays very nicely with Unity’s Resolve method.

Tags:   asp.net mvc 2, unity 2.0, update, correction, dependency injection
Categories:   ASP.NET MVC | Unity
Actions:   | Ping backs (1)

Dependency injection in ASP.NET MVC with Unity IoC Container

Friday, 25 December 2009 18:48 by Rickard Nilsson

Update!

Download sample project MvcWithUnity.VS2010.zip (727,52 kb)

Download sample project MvcWithUnity.VS2008.zip (546,33 kb)

Update! This still apply in ASP.NET MVC 2 and Unity 2.0. Read more here...

Enabling truly easy testability with ASP.NET MVC Controllers requires a Dependency Injection container. This post is about showing a more real life example of combining Unity with ASP.NET MVC Controllers than the standard demo. Unity is the IoC Container from Microsoft Patterns & Practices and ships as a part of Enterprise Library as well as a stand alone on Codeplex.

We start with the unit test which drives the design of the controller.

[TestMethod]
public void Post_PostWithSlugExists_ReturnsResultWithPostAsModel() {
    controllerContext.RouteData.Values.Add("slug", ValidSlug);
    var expected = MockRepository.GenerateStub<IBlogPost>();
    var blogPosts = new[] {expected};
    blogPostService.Expect(s => s.GetPostWhereSlugEquals(slug))
                   .Repeat.AtLeastOnce()
                   .Return(blogPosts);
    var controller = CreateController();

    var result = (ViewResult) controller.Post();
    Assert.AreEqual(expected, result.ViewData.Model);
}

Even though the test becomes a bit verbose it clearly states the intent of the controller’s Post method; given the right slug, a result is returned with a blog post as model.

Dependency Injection in ASP.NET MVC

In ASP.NET MVC every request starts in a controller which uses a set of dependencies to do its job. When we have applied Inversion of Control we can inject all of the controller’s dependencies either as a constructor argument or as a property setter. To fully take advantage of this technique we want the dependencies to be automatically injected without creating any of them in overloaded constructors or something like that. This is where the Controller Factory in ASP.NET MVC comes into play.

Controller Factory

In the System.Web.Mvc namespace lives the IControllerFactory which implementation is used by the framework to create controller instances. We can use this to swap out the default one and replace it with our own controller factory which uses Unity to create controllers instead.

Instead of implementing all of the IControllerFactory functionallity we can extend the System.Web.Mvc.DefaultControllerFactory and only override what we need.

public class UnityControllerFactory : DefaultControllerFactory {
    private readonly IUnityContainer container;

    public UnityControllerFactory(IUnityContainer container) {
        this.container = container;
    }

    protected override IController GetControllerInstance(Type controllerType) {
        return container.Resolve(controllerType) as IController;
    }
}

In the Global.asax, called MvcApplication in ASP.NET MVC by default, we create our Unity container and tells the MVC framework to use our UnityControllerFactory instead of the default one.

// in Global.asax.cs
protected void Application_Start() {
    RegisterRoutes(RouteTable.Routes);

    var container = new UnityContainer();
    var controllerFactory = new UnityControllerFactory(container);
    ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}

PostController

To illustrate why this is so powerful we will implement a controller that handles requests for blog posts, such as the one you’re reading right now. For this example the controller only handles requests for single blog posts using the post’s slug as identity. A slug is the post’s title made url friendly (e.g. "Dependency-injection-in-ASPNET-MVC-with-Unity-IoC-Container” for this post). The PostController has a dependency on an IBlogPostService which it uses to lookup the blog post to send to the view.

public class PostController : Controller {
    private readonly IBlogPostService blogPostService;

    public PostController(IBlogPostService blogPostService) {
        this.blogPostService = blogPostService;
    }

    public ActionResult Post() {
        var slug = GetSlug();
        var post = blogPostService.GetPostWhereSlugEquals(slug);
        return View(post);
    }

    private string GetSlug() {
        return RouteData.GetRequiredString("slug");
    }
}

Strongly-typed views

The Post action returns an ActionResult with the post a the model. We can use strongly-typed views to get intellisense in the aspx-file.

<%@ Page /*...*/ Inherits="ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%=Model.Title %>
asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%=Model.Title %>h2>
    <p>
        <%=Model.Body %>
    p>
    <p><%=Html.PostActionLink("Permalink", Model) %>p>
    <p><a href="/2009/10/10/fail">fail linka>p>
asp:Content>

Notice how the view inherits from ViewPage which is key to make the model type of IBlogPost. Then we can use the Post properties to render the blog post in the view.

Conclusion

Combining ASP.NET MVC with Unity or your IoC Container of choice makes your controllers much more easily testable. You only state your classes dependencies as constructor parameters or properties and the container will do the wiring for you. The gives you time to focus on the program logic and the interaction between its components.

Tags:   dependency injection, inversion of control, ioc container, unity, patterns & practices, testing
Categories:   ASP.NET MVC | Unit testing
Actions:   | Ping backs (1)

How to unit test code which depends on HttpContext.Current.Server

Wednesday, 11 November 2009 22:33 by Rickard Nilsson

Much of the legacy ASP.NET code I’ve seen is littered with calls to methods on the HttpServerUtility class,

Server.MapPath(…)

is only one such method. This makes it really hard to test. We need to be able to fake the MapPath method to return exactly what we want without doing the actual file mapping on disk.

Why, if your suite has thousands of tests and many calls IO or datebases, the tests will run slowly, and the developers on the team won’t run them as often. Ultimately, you may loose your investment in automated testing because it isn’t providing the promised feedback.

  • First of all, if the code is in the code behind of an aspx-file we need to extract as much as possible into its own class, which can be newed up in a unit test.
  • Second of all, we need to extract all external dependencies of the class such that fakes can be injected.

If the code behind code calls Server.MapPath() it is actually calling the Server property on the Page base class which returns HttpContext.Current.Server. This is an instance of the HttpServerUtility class, which is sealed and thus pretty impossible to fake out*.

Solution

In the namespace System.Web.Abstractions, which is part of ASP.NET 3.5, lives an abstraction of the HttpServerUtility, called HttpServerUtilityBase. It has a concrete implementation named HttpServerUtilityWrapper that takes an HttpServerUtility instance as a constructor parameter, as follows:

public sealed class HttpServerUtility {
    // ...
}

public abstract class HttpServerUtilityBase {
    // ...
}

public class HttpServerUtilityWrapper : System.Web.HttpServerUtilityBase {
    public HttpServerUtilityWrapper(HttpServerUtility httpServerUtility) {} 
    // ...
}

By leveraging a simple form of dependency injection we can preserve the old code as a first step of refactoring, and using an overloaded constructor to inject the fake object in our unit test.

public class Presenter {
    private HttpServerUtilityBase Server;

    public Presenter(HttpServerUtilityBase httpServerUtility) {
        Server = httpServerUtility;
    }

    public Presenter() {
        Server = new HttpServerUtilityWrapper(HttpContext.Current.Server);
    }

    public void PageLoad() {
        var path = Server.MapPath(…)
    }
}

Now, in a unit test for the Presenter class we can inject a fake server utility, which won’t call any IO.

[Test]
public void PageLoad_WhenCalled_ExpectedBehavior() {
    var fakeServerUtility = new HttpServerUtilityFake();  // implemented in the test suite
    var presenter = new Presenter(fakeServerUtility);
    presenter.PageLoad();
    // Assert expected behavior
}

Instead of implementing your own fake you can easily use your preferred isolation (mocking) framework of choice.

Conclusion

The goal is to isolate the class under test from all of its dependencies, weather they call IO, a database, a third party component, or even statics or touch static state. The point is that we want to assert that the class under test behaves as expected, not how the underlying framework behaves.

By leveraging the System.Web.Abstractions namespace we can preserve much of the existing ASP.NET code while covering it with tests.

_________
* Unless using TypeMock Isolator

Tags:   asp.net 3.5, unit test, agile, fakes, httpcontext, dependency injection
Categories:   Agile | ASP.NET 3.5 | Unit testing
Actions:  
 
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© 2008-2011 rickardnilsson.net
Creative Commons-licens