One thing, that I have seen done wrong in so many ways, is DI in relation to ASP.NET MVC. Just to get things straight for everyone – including those, who have been living under a rock for the last 30 years – here’s a glossary:

  • Dependency injection (DI) – is exactly what it says, i.e. dependencies are injected. So your business methods don’t just instantiate order processors, they have them injected for them to use.
  • Inversion of control (IoC) – is when program flow is no longer just sequential. In many cases just a fancy term for a callback. In this case, it signifies that your classes may call stuff on instances on other classes, that are handed to them – which happens by DI.
  • IoC container – is a thing, that facilitates the above and removes the pain.

Quick, off the top of my head implementation of an ASP.NET MVC action method

public ActionResult Index()
{
    var productService = new ProductService();
    var productsOnSale = productService.GetProductsOnSale();
    return View("Index", new ProductListViewModel(productsOnSale);
}

Now what happens when we want to test this? Well, we definitely need the database to be there, otherwise we will probably get some nasty SqlException stuff happening. There may be other stuff going on, we don’t know. Or even if we know now, we will not have a clue in a few months! – because what if some class, on which our ProductService depends, changes? Or changes its dependencies? The product service is tightly coupled to everything that is architecturally beneath it. We need inversion of control!

Naïve IoC/DI example

public ActionResult Index()
{
    var sessionProvider = new NHibernateSessionProvider();
    var productRepository = new ProductRepository(sessionProvider);
    var productIsOnSaleSpecification = new ProductIsOnSaleAccordingToSomeFunkyRulesSpecification();
    var productService = new ProductService(productRepository, productIsOnSaleSpecification);
    var productsOnSale = productService.GetProductsOnSale();
    return View("Index", new ProductListViewModel(productsOnSale);
}

Now, we have DI-enabled our service layer. It can be seen that the repository gets its NHibernate ISession from a session provider, that can probably be configured with a connection string somewhere. And we have a complex business rule inside a specification, and a service to use the repository and the specification together. This is much better, because all dependencies are explicit and injected from the outside. But this code is still not perfect – there’s way too much going on, the classes are all concrete, and there is no way to test the action method without instantiating all this stuff. And what happens when the product service is used in 100′s of places in the system, and suddenly it needs another specification in its constructor to decide whether the current user can be given a rebate? Damn! Back to work… let’s try again:

Service locator IoC/DI example

public ActionResult Index()
{
    var productService = MyContainer.Resolve<IProductService>();
    var productsOnSale = productService.GetProductsOnSale();
    return View("Index", new ProductListViewModel(productsOnSale);
}

Now it’s much clearer again. But what is MyContainer? Well, it’s actually pretty simple: it’s a generic factory! And this time we are using the factory to supply a dependency when we need it and let the factory decide where to get it. Then it may deliver a new instance, an instance from a pool, an instance tied to the current HttpRequest or a singleton or whatever it feels like. This is the service locator pattern, and it’s better than the second example, but still – your code will be cluttered with calls to your container, so unit testing will not be as easy because your need to have a container in place or mock it.

This brings me to how to do it with ASP.NET MVC – the important thing is that we have one single call to container.Resolve<...>. We do it by taking control over how controllers are created, because the controller creation is the single entry point into as ASP.NET MVC application. Here goes:

ASP.NET MVC with IoC/DI

global.asax
void Application_Start()
{
    // RegisterRoutes(...)
 
    // installs our controller factory at application startup
    ControllerBuilder.SetDefaultControllerFactory(typeof(MyControllerFactory));
}
MyControllerFactory.cs
public class MyControllerFactory : IControllerFactory
{
    static IContainer myContainer = GetContainerInstanceFromSomewhere();
 
    public IController CreateController(RequestContext context, string name)
    {
        // looks up controller registered under lowercase key - e.g. "home" for HomeController
        var key = name.ToLowerInvariant();
        return myContainer.Resolve(key);
    }
 
    public void ReleaseController(IController controller)
    {
        // releases any IDisposables inside this controller
        MyContainer.Release(controller);
    }
}

And now – the best thing about DI: The class is pure! Look!

ProductsOnSaleController.cs
public class ProductsOnSaleController : Controller
{
    public ProductsOnSale(IProductService productService)
    {
        this.productService = productService;
    }
 
    public ActionResult Index()
    {
        var productsOnSale = productService.GetProductsOnSale();
        return View("Index", new ProductListViewModel(productsOnSale);
    }
}

It is plain and simple, depending on a product service only, which gets automatically injected by the container. Easy to test, easy to extend. And we are probably going to write 100′s and 1000′s of action methods, so we are going to save a lot of work and grief on that account – thanks to DI and IoC.

I think this is THE way to do dependency injection in ASP.NET MVC controllers. I will show in another post how you can configure Castle Windsor with ASP.NET MVC to support multiple configurations (e.g. IEmailService is FakeLoggingEmailService on the developers’ machines and RealLiveSmtpEmailService in a production environment.

Apr 152009

Usually, when writing code, you adhere to some conventions on how your stuff should work. At least I hope you do – otherwise your code is probably a mess!

Sometimes, these conventions can be enforced by using some patterns to allow for compile-time checking – one example, that I can think of right now, is using the visitor pattern to implement multiple dispatch, which is explored a little bit in another post.

But what about conventions, that can only be checked at runtime? Well, how do we usually check stuff that can only be checked at runtime? – by writing tests, of course!

One project I am currently involved in, is written in ASP.NET MVC. All form posts are done using the automatic binding features of the framework, and I am following the convention that the names of my view models should end in “Form” – so as to enabling me to easily distinguish my form posting DTOs from my other view models. What is more natural, then, than performing the following test:

[Test]
public void ActionParametersAreEitherPrimitiveTypesOrTruePocos()
{
	var assembly = Assembly.GetAssembly(typeof (HomeController));
	var types = assembly.GetTypes().ToList();
 
	types
		.FindAll(ThatIsConcreteController)
		.SelectMany(t => t.GetMethods().ToList().FindAll(ControllerActions))
		.ToList()
		.ForEach(CheckMethodInfo);
}
 
bool ControllerActions(MethodInfo info)
{
	return info.IsPublic && typeof(ActionResult).IsAssignableFrom(info.ReturnType);
}
 
void CheckMethodInfo(MethodInfo info)
{
	var parameters = info.GetParameters().ToList();
 
	parameters.ForEach(p => CheckParameterType(info, p));
}
 
void CheckParameterType(MethodInfo methodInfo, ParameterInfo parameterInfo)
{
	Assert.IsTrue(IsPrimitiveType(parameterInfo) || IsFormType(parameterInfo),
	              string.Format(
	              	"Action {0} of {1} has parameter of type {2} which is invalid. Use only true pocos from the view models assembly.",
	              	methodInfo.Name,
	              	methodInfo.DeclaringType.Name,
	              	parameterInfo.ParameterType.Name));
}
 
bool IsFormType(ParameterInfo info)
{
	var type = info.ParameterType;
 
	return
		type.Assembly == Assembly.GetAssembly(typeof (LogInForm))
		&& type.Name.EndsWith("Form");
}
 
bool IsPrimitiveType(ParameterInfo info)
{
	// add mores types here if they should be allowed as well
	return
		new List<Type>
			{
				typeof (int),
				typeof (string),
				typeof(int?),
				typeof(Guid)
			}.Contains(info.ParameterType);
}
 
bool ThatIsConcreteController(Type type)
{
	return typeof(Controller).IsAssignableFrom(type) && !type.IsAbstract;
}

That is, I am running through all controller types, getting all actions, and checking the the parameter types are either in the array of accepted types (IsPrimitiveType) or a “true poco” (which in this application is a simple view model whose name ends with “Form” and comes from the right assembly).

This way, I will always know which types are used to deserialize forms. Great! But what about that pesky MissingMethodException whenever I forget to provide a public default contructor in my form models? Easy as cake! That part is checked by the following test:

[Test]
public void AllFormModelsHavePublicDefaultConstructor()
{
	var assembly = Assembly.GetAssembly(typeof (LogInForm));
	var types = assembly.GetTypes().ToList();
 
	types
		.FindAll(ThatCouldBePoco)
		.FindAll(ThatSatisfiesPocoNamingConvention)
		.ForEach(AssertHasPublicDefaultConstructor);
}
 
bool ThatCouldBePoco(Type type)
{
	return type.IsClass
	       && !type.IsAbstract;
}
 
bool ThatSatisfiesPocoNamingConvention(Type type)
{
	var name = type.Name;
 
	return name.EndsWith("Form");
}
 
void AssertHasPublicDefaultConstructor(Type type)
{
	var constructors = type.GetConstructors().ToList();
 
	Assert.IsTrue(constructors.Exists(IsPublicDefaultConstructor),
	              string.Format("Poco type {0} does not provide a public default constructor.",
	                            type.Name));
}
 
bool IsPublicDefaultConstructor(ConstructorInfo info)
{
	var parameters = info.GetParameters();
 
	return parameters.Length == 0;
}

These two tests combined, will assert that nothing will go wrong when submitting forms in my ASP.NET MVC project. That’s just nifty! And I really like the notion that I am helping future me.

In ASP.NET MVC you may “tag” your actions with attributes derived from ActionFilterAttribute and automatically have their OnActionExecuting and OnActionExecuted methods called before and after the framework invokes your action, thus achieving a simple form of method interception by using attributes.

Pretty simple model, but it falls apart if you are using an IoC container to wire things up. Moreover, having application logic embedded in properties is sort of icky. It just so happens that we can solve both problems and end up with a pretty nice solution at the same time :-)

First, create the interface you wish to use to denote an action filter – e.g. something like this:

public interface IActionFilterService
{
	void Before(IBeforeActionContext context);
	void After(IAfterActionContext context);
}
 
public interface IBeforeActionContext
{
}
 
public interface IAfterActionContext
{
	void ProvideViewData(IDictionary<string, object> data);
}

Note that I have used interfaces for the arguments. This allows us to decouple the action filter from the framework classes, thus making our stuff more easily testable.
In this example I have only put one method – ProvideViewData – on IAfterActionContext, allowing my action filters to insert additional key-value-pairs into the ViewData. More methods should of course be added if they are needed.

Then, create the actual action filter attribute, and make it accept a type as ctor argument – e.g. like this (assuming I want to resolve dependencies through the Windsor container installed as my controller factory):

public class ServiceFilterAttribute : ActionFilterAttribute
{
	readonly Type serviceType;
	readonly IWindsorContainer container = WindsorControllerFactory.Instance.Container;
 
	public ServiceFilterAttribute(Type serviceType)
	{
		this.serviceType = serviceType;
	}
 
	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		((IActionFilterService)container
			.Resolve(serviceType))
			.Before(new BeforeActionContext(filterContext));
	}
 
	public override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		((IActionFilterService)container
			.Resolve(serviceType))
			.After(new AfterActionContext(filterContext));
	}
}

And then implement the before and after argument classes – e.g. like this:

class BeforeActionContext : IBeforeActionContext
{
	readonly ActionExecutingContext context;
 
	public BeforeActionContext(ActionExecutingContext context)
	{
		this.context = context;
	}
}
 
class AfterActionContext : IAfterActionContext
{
	readonly ActionExecutedContext context;
 
	public AfterActionContext(ActionExecutedContext context)
	{
		this.context = context;
	}
 
	public void ProvideViewData(IDictionary<string, object> data)
	{
		var viewResult = context.Result as ViewResult;
 
		if (viewResult == null) return;
 
		foreach (var pair in data)
		{
			viewResult.ViewData.Add(pair);
		}
	}
}

Now you may use the action filter like this:

[ServiceFilter(typeof(IProvideProductCount))]
public ViewResult Index()
{
	return View();
}

where your IProvideProductCount will have all its dependencies automatically resolve by the container. That’s just sweet :-)

In this example I made this simple implementation:

public class ProvideProductCount : IProvideProductCount
{
	readonly IProductRepository productRepository;
 
	public ProvideProductCount(IProductRepository productRepository)
	{
		this.productRepository = productRepository;
	}
 
	public void Before(IBeforeActionContext context)
	{
	}
 
	public void After(IAfterActionContext context)
	{
		var count = productRepository.Count();
 
		context
			.ProvideViewData(new Dictionary<string, object>
			                 	{
			                 		{"productCount", count}
			                 	});
	}
}

- thus allowing any views rendered from an action tagged with [ServiceFilter(typeof(IProvideProductCount))] to show how many products we have.

If your action filter attributes need arguments, then it’s another story. I wonder how one could get around to implement that?

Once upon a time (back before preview 5 of ASP.NET MVC), you could link to controller actions in a strongly typed manner, like so:

Go <%= Html.ActionLink<HomeController>(c => c.Index(), "home") %>

- but due to some design decision, this particular overload is not immediately available anymore.

Fortunately, it has not been deleted from the world – it has just been moved to the Microsoft.Web.Mvc assembly – also known as ASP.NET MVC Beta Futures which is sort of an experimental playground where the MVC team put features that might be implemented as part of the official MVC release.

So, if you realize that your routes are mapped 1:1 directly to your controller methods, then why not reference the aforementioned assembly and add the following to your web.config:

// system.web / compilation / assemblies
<add assembly="Microsoft.Web.Mvc"/>
 
// system.web / pages / namespaces
<add namespace="Microsoft.Web.Mvc"/>

- thus bringing back the sweet strongly typed lambda-enabled action link overload.

May 172008

Ever wanted to use your own custom HtmlHelper extensions inside your NHaml views? I wanted that, but I got this error:

error CS1061: ‘System.Web.Mvc.HtmlHelper’ does not contain a definition for ‘WhyOhWhy’ and no extension method ‘WhyOhWhy’ accepting a first argument of type ‘System.Web.Mvc.HtmlHelper’ could be found (are you missing a using directive or an assembly reference?)

The problem was that NHaml would not know that there existed some extensions of the HtmlHelper class in some obscure assembly somewhere inside my web app. To do this, you need to tell NHaml exactly which assembly and which namespaces to include in its search. Here is how to do it:

In your web.config, beneath the <configSections> node, add this

<section name="nhamlViewEngine" type="MvcContrib.NHamlViewEngine.Configuration.NHamlViewEngineSection, MvcContrib.NHamlViewEngine" />

- and then outside of <configSections>, add this:

<nhamlViewEngine configSource="NHaml.config"/>

This will cause NHaml.config to be included. We could just have embedded the configuration inside the web.config file, but we want to make separate NHaml.config files for each environment we want to deploy our application in. Then we can turn on NHaml’s compiled view caching feature by flicking the production attribute.

An example NHaml configuration is something like this:

<nhamlViewEngine production="false">
  <views>
    <assemblies>
      <add assembly="MyAssembly" />
    </assemblies>
    <namespaces>
      <add namespace="MyAssembly.HtmlHelperExtensions" />
      <add namespace="MyAssembly.EvenMoreHtmlHelperExtensions" />
    </namespaces>
  </views>
</nhamlViewEngine>

Suddenly you will gain access to everything inside the specified namespaces inside your NHaml templates. Nifty!

© 2010 mookid on code Suffusion WordPress theme by Sayontan Sinha