An interesting topic, that I always love to discuss, is how to find a balance between building a pure domain model and being pragmatic and getting the job done. It just so happens, that getting the job done, and being able to add features to a system quickly, usually conflicts with my inner purist, who really wishes to keep my domain model and services oblivious of everything infrastructure-related.

Usually, I go for pragmatism. Not only because I’m lazy, but also because I think it’s funny to come up with solutions that accelerate development, and generally make the sun shine brighter.

Actually, this post should have been #2 in a series called “Polluting My Domain”, and this post should have been #1, because in #1 I showed how I usually use attributes to give hints to the automapper in Fluent NHibernate – e.g. [Cascade] on a relation to configure NHibernate to cascade operations across that relation, or [Indexed("ix__something")] to make that column be indexed in the database, or [Encrypted] to make that particular property be backed by an encrypting IUserType.

This post, however, will show a pragmatic, elegant and flexible way to make component registration easy in an IoC container.

Most IoC containers that I know of can be configured with XML and through some kind of more or less fluent API in code. I’ll spare you the XML, so I’ll just show a small example on Castle Windsor’s fluent API:

container.Register(Component.For<ISomeService>().ImplementedBy<SomeServiceImplementation>())

or you can perform multiple registrations like this:

container.Register(AllTypes.FromAssemblyContaining<SomeService>()
                                .BasedOn<IService>()
                                .WithService.FromInterface())

This is all fine and dandy, but I think the fluent API becomes pretty complicated when you throw customized registrations per customer and/or environment into the mix – mostly because it will become kind of obscure which services get registered where.

Therefore, one of the first things I have put in my recent projects, have been a registration routine based on attributes. Pretty simple, and yes, it does pollute my domain services with infrastructure-related stuff, but this is a great example where I prefer pragmatism and simplicity over purity.

My most recent project has two attributes, ServiceAttribute and RegisterInAttribute that look something like this:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ServiceAttribute
{
    readonly Type serviceType;
 
    public ServiceAttribute()
    {
    }
 
    public ServiceAttribute(Type serviceType)
    {
        if (serviceType == null) throw new ArgumentNullException("serviceType");
        this.serviceType = serviceType;
    }
 
    public Type ServiceType
    {
        get { return serviceType; }
    }
}
 
public enum Environment
{
    Development,
    Test,
    Staging,
    Production,
}
 
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RegisterInAttribute
{
    readonly Environment environment;
 
    public RegisterInAttribute(Environment environment)
    {
        this.environment = environment;
    }
 
    public Environment Environment
    {
        get { return environment; }
    }
}

and then the registration code looks like this:

public class ComponentRegistrar
{
	public static void RegisterComponentsFromAssemblyOf<TSomeType>(IWindsorContainer container, 
                                                                       Environment environment)
	{
		var components = typeof(TSomeType).Assembly.GetTypes()
					.Where(t => ShouldBeRegistered(t, environment))
					.SelectMany(t => ToComponentRegistrations(t));
 
		container.Register(components);
	}
 
	static IEnumerable<TAttribute> GetAttributes(ICustomAttributeProvider provider)
	{
		return provider.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
	}
 
	static bool ShouldBeRegistered(ICustomAttributeProvider provider, Environment environment)
	{
		var attributes = GetAttributes<RegisterInAttribute>();
 
		return !attributes.Any() || attributes.Any(a => a.Environment == environment)
	}
 
	static IEnumerable<IRegistration> ToComponentRegistrations(Type type)
	{
                var serviceType = a.ServiceType ?? type;
 
		return GetAttributes<ServiceAttribute>(type)
				.Select(a => Component.For(serviceType)
							.ImplementedBy(type)
							.Lifestyle.Transient);
	}
}

So, having established the current value of environment, my component registration will look like this:

var environment = DetermineEnvironmentFromAppSettingsOrSomethingLikeThat();
 
var container = new WindsorContainer();
ComponentRegistrar.RegisterComponentsFromAssemblyOf<HomeController>(container, environment);
ComponentRegistrar.RegisterComponentsFromAssemblyOf<SomeDomainService>(container, environment);
ComponentRegistrar.RegisterComponentsFromAssemblyOf<SomeInfrastructureService>(container, environment);
 
// yay!

- and that’s it! But the best of it is that adding services to the system now becomes a breeze – check this out – registering a concrete type, offering itself as a service:

[Service]
public class HomeController : Controller
{
    // (....)
}

- and here’s registering different stuff depending on the environment:

[Service]
[RegisterIn(Environment.Development)]
public class DebugController : Controller
{
    // (....)
}
 
[Service(typeof(IMailSender))]
[RegisterIn(Environment.Production)]
public class SmtpMailSender : IMailSender
{
    // (...)
}
 
[Service(typeof(IMailSender))]
[RegisterIn(Environment.Staging)]
public class FakeSmtpMailSender : IMailSender
{
    // (...)
}
 
[Service(typeof(IMailSender))]
[RegisterIn(Environment.Development)]
[RegisterIn(Environment.Test)]
public class LoggingMailSender : IMailSender
{
    // (...)
}

This way of registering component has proven to me several times to be a simple and nifty way of managing the differences between environments, and even differences between customers (which would require a few extensions to the example above though), still being able to add services to the system quickly.

Another benefit is that it’s pretty clear what happens, even to developers who might not be that experienced in using IoC containers. If I were the only developer on a project, I would probably prefer component registration based on conventions, but when you have a team, you sometimes need to make some things more explicit.

NServiceBus for dummies who want to be smarties 4… fourth post, this time on how to incorporate NServiceBus as a backend in an ASP.NET MVC application.

How to create the projects

First, create a new ASP.NET MVC project. I assume you know how to use an IoC container to instantiate controllers, and that you know how to configure your container (otherwise, there are plenty of information available – e.g. here and here), so I will just show this simple snippet on how to build the bus and put it in the container:

In Application_Start:

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(CreateWindsorContainer()));

- and then the container can be created like this:

    IWindsorContainer CreateWindsorContainer()
    {
      var container = new WindsorContainer();
 
      // register controllers and other stuff here
 
      Configure.WithWeb()
        .CastleWindsorBuilder(container)
        .XmlSerializer()
        .MsmqTransport()
          .IsTransactional(true)
          .PurgeOnStartup(true)
        .MsmqSubscriptionStorage()
        .UnicastBus()
        .CreateBus()
        .Start();
 
      return container;
    }

Notice the call to the extension method CastleWindsorBuilder? It comes from the assembly NServiceBus.ObjectBuilder.CastleWindsor.dll which is included with NServiceBus – it provides the adapters necessary for NServiceBus to a) register everything it discovers (like e.g. all your implementations of IMessageHandler<>), and b) pull instances when needed thus supplying dependencies during object activation. This way of supporting multiple IoC containers just plain ROCKS!

At this point NServiceBus has registered itself and resolved all message handlers found in the current web application’s bin directory (Configure.WithWeb() as opposed to Configure.With()) in the supplied IoC container, and since I am pulling all my controllers from Windsor, I can jump directly to implementing my HomeController:

  public class HomeController : TxBaseController
  {
    readonly IBus bus;
 
    public HomeController(IBus bus)
    {
      this.bus = bus;
    }
 
    [AcceptVerbs(HttpVerbs.Post)]
    public RedirectToRouteResult DoSomething(string text)
    {
      bus.Send(new SomethingHappened {Message = text});
 
      return RedirectToAction("Index");
    }
 
    [AcceptVerbs(HttpVerbs.Post)]
    public RedirectToRouteResult DoSomethingBad(string text)
    {
      bus.Send(new SomethingHappened { Message = text });
 
      throw new ApplicationException("oh noes!");
    }
 
    public ViewResult Index()
    {
      return View();
    }
  }

As you can see, I implemented two actions responding to a HTTP post, both sending a message to the backend, but DoSomethingBad throws an exception, in which case i do not want the message to actually be sent.

My view is just a trivial (Spark) view with two forms:

<use master="Site"/>
 
<h1>DoSomething</h1>
<form method="post" action="!{Url.Action("DoSomething")}">
  Enter text: <input type="text" name="text" />
  <input type="submit" value="Send" />
</form>
 
<h1>DoSomethingBad</h1>
<form method="post" action="!{Url.Action("DoSomethingBad")}">
  Enter text: <input type="text" name="text" />
  <input type="submit" value="Send" />
</form>

And then I made a simple backend with one message handler:

  public class HandleSomethingHappened : IMessageHandler<SomethingHappened>
  {
    public void Handle(SomethingHappened message)
    {
      Console.WriteLine("Something happened: {0}", message.Message);
    }
  }

Now, to check if things work, I navigate to /home/index, which on my computer looks like this:

dosomething

- and then I enter the text “WHEE!” into the first text field and press “Send”, yielding the following in my backend’s console window:

fantastic

Which is great! My backend receives messages from my web application, so now I can put all kinds of heavy calculations and processesing and whatnot in there, to be computed outside of web requests.

Now, what if something bad happens during the web request, and we do not want any messages to actually be sent? Well, if I enter a text into the other text field and submit it (to the DoSomethingBad action of my HomeController), nothing happens on the backend! Why is that?

Simply because I have started a TransactionScope in my controller layer supertype, TxBaseController, ensuring that all controller actions are run inside a (possibly distributed) transaction! It looks like this:

  public abstract class TxBaseController : Controller
  {
    TransactionScope currentTx;
 
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      currentTx = new TransactionScope();
 
      base.OnActionExecuting(filterContext);
    }
 
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      base.OnActionExecuted(filterContext);
 
      var exceptionHappened = filterContext.Exception != null;
      var exceptionWasHandled = filterContext.ExceptionHandled;
 
      if (!exceptionHappened || exceptionWasHandled)
      {
        currentTx.Complete();
      }
 
      currentTx.Dispose();
    }
  }

- and since message queueing plays along nicely with the currently ongoing ambient transaction (which e.g. the incredible NHibernate ALSO does), this transaction scope will make sure that everything just works!

Conclusion

That concludes today’s “NServiceBus for dummies who want to be smarties”. This one was on how to actually put NServiceBus to use as a simple backend for an ASP.NET MVC web application. Freaking easy, right?! Next time I will show how to put sagas to use by implementing one of the workflows of a typical web application.

Almost always, when writing even the simplest of systems, the need arises for some kind of event publishing/subscription mechanism. There are of course many ways to achieve this, but I have found that Castle Windsor can provide everything that I need to build a simple, yet incredibly powerful event bus.

Consider this example from the real world: mortgage deeds follow many paths through our mortgage deed administration system, and one of them is purchase for the administrator’s own portfolio. Upon recording the purchase, it is crucial that the debtors are enlisted in our subscription at the Central Office Of Civil Registration (CPR in Danish), allowing us to receive updates whenever people change names or move without telling us.

A naive implementation of the Record method on the Purchase could look like this:

public class Purchase : Transaction
{
	// ...
	public virtual void Record()
	{
		// ...
		//
		// and then:
		foreach(var debtor in MortgageDeed.CurrentDebtors)
		{
			Enlist(debtor.LegalEntity);
		}
	}
 
	void Enlist(LegalEntity entity)
	{
		ServiceLocator.Resolve<ICprEnlistment>().Enlist(entity);
	}
}

- but this is ugly! Enlisting the debtors has no direct relation to the logic of how to record a purchase, and when this requirement came, this implementation caused numerous tests to break. You could of course argue that our tests should not rely on the record method, but that was however the case, and it was a real P.I.T.A. to implement this.

Moreover, this approach forces us to grab our service locator inside a domain entity, which is really bad for too many reasons to mention here.

What we SHOULD have done, and what I have been doing ever since, is to create a simple event bus that resolves handlers to messages through Windsor (actually directly through the kernel because it is automatically injected). This way, I could have implemented the record method like this:

public class Purchase : Transaction
{
	// ...
	public virtual void Record()
	{
		// ...
		//
		// and then:
		EventBus.Publish(new PurchaseRecorded(Id));
	}
}

- and then this method would never change again (at least not for the wrong reasons)…

Then I have my simple event bus mediator (just an ounce of indirection, allowing my entities to be unaware of the service locator):

public static class EventBus
{
	[ThreadStatic]
	static IBus bus;
 
	public static void Publish(object message)
	{
		GetBus().Publish(message);
	}
 
	static IBus GetBus()
	{
		return bus ?? (bus = CreateBus());
	}
 
	static IBus CreateBus()
	{
		return EventBusConfiguration.TestMode
			? new StubBus()
			: ServiceLocator.Resolve<IBus>();
	}
}
 
public static class EventBusConfiguration
{
	public static bool TestMode { set; get; }
}

- which, depending on the bool inside the static EventBusConfiguration class, will be either a fake bus that swallows all its messages, or the real deal:

public class EventBus : IEventBus
{
	IKernel kernel;
 
	public EventBus(IKernel kernel)
	{
		this.kernel = kernel;
	}
 
	public void Publish(object message)
	{
		// get type of published message
		var messageType = message.GetType();
 
		// close the handler type to be subscribers
		// of this exact type of message
		var handlerType = typeof(ISubscribesTo<>)
			.MakeGenericType(messageType);
 
		// make MicroKernel do its thing
		var handlers = kernel.ResolveAll(handlerType);
 
		// invoke handlers
		foreach(object handler in handlers)
		{
			var method = handler.GetType().GetMethod("Handle");
			method.Invoke(object, new [] {message});
 
			kernel.ReleaseComponent(handler);
		}
	}
}

This means that subscribing to a message is as simple as registering implementations of this:

public interface ISubscribesTo<T>
{
	void Handle(T message);
}

in my Windsor Container, e.g. the handler that enlists people in our subscription at the Central Office Of Civil Registration:

public class EnlistLegalEntitiesWithCpr : ISubscribesTo<PurchaseRecorded>
{
	ICprEnlistment cprEnlistment;
	ITransactionRepository transactionRepository;
 
	public EnlistLegalEntitiesWithCpr(ICprEnlistment cprEnlistment, ITransactionRepository transactionRepository)
	{
		this.cprEnlistment = cprEnlistment;
		this.transactionRepository = transactionRepository;
	}
 
	public void Handle(PurchaseRecorded message)
	{
		var purchase = transactionRepository.FindById(message.Id);
		var debtors = purchase.MortgageDeed.CurrentDebtors;
 
		foreach(var debtor in debtors)
		{
			cprEnlistment.Enlist(entity);
		}
	}
}

This is really cool, because it allows one to build systems where logic is deliciously decoupled, and you can add stuff, and then some more stuff, and the new stuff will not break the old stuff, because it doesn’t interfere with it.

Moreover, if you feel like extending it a little bit, it shouldn’t take that much of an effort to publish the events into a message queue for other systems to handle. If, for example, it took a while to process something, then I would definitely benefit from letting another process take care of that while my web request continues. Or if I wanted to update my data warehouse, I would build an aggregator in another process that did batch updates of the warehouse.

Oh, and this is one of the reasons that I would not hesitate to choose Castle Windsor if I were allowed to bring only one thing to a deserted island… you can build almost anything with a cool IoC container.

My favorite hook in the ASP.NET MVC framework is the controller factory. I like it so much because it serves as a very simple entry point to the application, thus providing the perfect place to insert an IoC container. My container of choice is Castle Windsor – not because I have tried any other container – I really can’t say that I have – but because I just happened to be introduced by a colleague to Windsor, and I have yet to experience anything it can’t do for me!

An ASP.NET MVC controller factory is an implementation of the IControllerFactory interface – a simple interface with two methods: one that provides an IController given a string and some more stuff, and one that allows the controller to clean up any resources it might have allocated. The interface looks like this:

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

As you can see, it provides a means to return a controller, given all sorts of information about the current request and what could be resolved as the controllerName from the request URL.

ASP.NET MVC accesses the controller factory via the ControllerBuilder class – so if we want to provide our own controller factory, we must install the factory before any requests get served. An obvious place to do this, is the Application_Start method inside the global.asax.cs file. This way our controller factory will be installed every time the web application starts up.

The controller factory can be set in two ways: 1) By providing the type of the factory, and 2) By providing an instance of the factory. Then it’s up to you if you want to let ASP.NET MVC instantiate the factory. I usually do it like this:

public void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
 
    ControllerBuilder.SetControllerFactory(typeof(MyControllerFactory));
}

- and let ASP.NET MVC instantiate and store a singleton instance of my factory.

My controller factory implementation looks like this:

public class MyControllerFactory : IControllerFactory
{
    IWindsorContainer container = CreateWindsorContainer();
 
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        return container.Resolve<IController>(controllerName.ToLowerInvariant());
    }
 
    public void ReleaseController(IController controller)
    {
        container.Release(controller);
    }
 
    static IWindsorContainer CreateWindsorContainer()
    {
        return new WindsorContainer("windsor.config");
    }
}

Very simple. It takes the string, that was resolved as the controller name – e.g. “home”, “hOme”, “HOME” or whatever – and converts it to lower case, and then it uses that to look up a controller in my container. This means that all my controllers are registered in the container, and they will have all their dependencies automatically resolved when the container creates each instance.

A controller registration might look like this:

<castle>
    <components>
        <component id="home" type="WebSite.Controllers.HomeController, WebSite" />
 
        <!-- more registrations here... -->
 
    </components>
</castle>

Simple – yet incredibly effective!

In the previous post I showed how easy it is to install an IoC container at the system boundary of your ASP.NET MVC application and have it resolve everything from there.

But what I did not show, was where the container came from – in the example, the container just pops out of nowhere on this line:

static IContainer myContainer = GetContainerInstanceFromSomewhere();

So how can we implement GetContainerInstanceFromSomewhere()?

Well, I like to do it like this:

IWindsorContainer GetContainerInstanceFromSomewhere()
{
    return new WindsorContainer("windsor.config");
}

Isn’t that easy? And then I have a folder structure in my ASP.NET MVC project that looks like this:

config-folder

It can be seen that I have a folder for each configuration of the system (development, test, prod) and one containing configuration files that are common for all configurations. For each configuration I have a hibernate.cfg.xml to configure NHibernate and a windsor.config which is loaded by the Windsor container in each particular configuration.

My development/windsor.config looks like this:

<castle>
  <include uri="file://controllers.config"/>
 
  <include uri="file://facilities.config"/>
 
  <include uri="file://factories.config"/>
 
  <include uri="file://repositories.config"/>
 
  <include uri="file://services.config"/>
 
  <!-- For this configuration only -->
  <components>
    <component id="services.ApplicationSettings"
               service="Model.Services.IApplicationSettings, Model.Services"
               type="WebSite.Stuff.DevelopmentMachineApplicationSettings, WebSite">
      <parameters>
        <DefaultEmailSender>noreply@website.com</DefaultEmailSender>
        <UrlBase>http://localhost:1766</UrlBase>
      </parameters>
    </component>
 
    <component id="services.EmailSender"
               service="Model.Services.IEmailSender, Model.Services"
               type="WebSite.Stuff.FakeLoggingEmailSender, WebSite" />
 
  </components>
</castle>

It can be seen that my development configuration is used to Cassini running on port 1766 :) moreover, it can be seen that my development configuration is using a fake, logging email sender, which – much as you would expect – only logs the content from emails that would otherwise have been sent.

Of course, the configuration files will not automatically be available to the web application the way they are organized now – therefore, my web project has a post-build task with the following two lines:

xcopy "$(ProjectDir)Config\common\*.*" "$(TargetDir).." /y
xcopy "$(ProjectDir)Config\development\*.*" "$(TargetDir).." /y

- thus copying the common configuration files along with the development configuration files to the base directory of the web application.

This also means that my build script must overwrite the development configuration files when building the system in a deployment configuration. It can be achieved as simple as this (using MSBuild):

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ApplicationFiles Include="ProjectName\WebSite\Default.aspx" />
    <ApplicationFiles Include="ProjectName\WebSite\Global.asax" />
    <ApplicationFiles Include="ProjectName\WebSite\Global.asax.cs" />
    <ApplicationFiles Include="ProjectName\WebSite\web.config" />
 
    <ApplicationFiles Include="ProjectName\WebSite\bin\*.*" />
  </ItemGroup>
 
  <PropertyGroup>
    <DestinationFolder>C:\Release\ProjectName</DestinationFolder>
    <ConfigurationFolder>ProjectName\WebSite\Config</ConfigurationFolder>
  </PropertyGroup>
 
  <Target Name="build">
    <MSBuild Projects="ProjectName\WebSite.sln" Targets="build" StopOnFirstFailure="true" Properties="Configuration=Release;">
      <Output TaskParameter="TargetOutputs" ItemName="AssembliesBuiltByChildProjects" />
    </MSBuild>
  </Target>
 
  <Target Name="deploy">
    <RemoveDir Directories="$(DestinationFolder)\Views;$(DestinationFolder)\Content;$(DestinationFolder)\bin;$(DestinationFolder)" />
    <MakeDir Directories="$(DestinationFolder);$(DestinationFolder)\bin;$(DestinationFolder)\Views;$(DestinationFolder)\Content" />
 
    <Copy SourceFiles="@(ApplicationFiles)" DestinationFolder="$(DestinationFolder)"/>
    <Exec Command="xcopy /d/e/f/y ProjectName\WebSite\Views\*.* $(DestinationFolder)\Views" />
    <Exec Command="xcopy /d/e/f/y ProjectName\WebSite\Content\*.* $(DestinationFolder)\Content" />
  </Target>
 
  <Target Name="deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\common\*.* $(DestinationFolder)" />
  </Target>
 
  <!-- Deployment configurations -->
  <Target Name="deploy_test" DependsOnTargets="build;deploy;deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\test\*.* $(DestinationFolder)" />
  </Target>
 
  <Target Name="deploy_prod" DependsOnTargets="build;deploy;deploy_common_configuration_files">
    <Exec Command="xcopy /d/e/f/y $(ConfigurationFolder)\prod\*.* $(DestinationFolder)" />
  </Target>
</Project>

Here I have define tasks for compiling the web site (“build”), deploying the binaries + views + content files (“deploy”), deploying common configuration files (“deploy_common_configuration_files”), and then one task for each deployable configuration: “deploy_test” and “deploy_prod”. This makes deploying the web site on my test web server as easy as running the following command:

msbuild /t:deploy_test

What is left now, is to make sure that the different sets of configuration files are valid in the sense that Windsor can resolve everything right. That is easily accomplished in the following NUnit test:

[TestFixture]
public class TestWindsorCanResolve
{
	const string ConfigFileRoot = @"..\..\..\WebSite\Config";
 
	[Test]
	public void CanMakeControllerInstances_test()
	{
		CheckConfiguration("test");
	}
 
	[Test]
	public void CanMakeControllerInstances_prod()
	{
		CheckConfiguration("prod");
	}
 
	static void CheckConfiguration(string configuration)
	{
		var controllerTypes = GetControllerTypes();
		var container = GetContainer(configuration);
 
		// using the given controllers and the given Windsor container - make sure
		// every controller can be instantiated
		controllerTypes.ForEach(t => container.Resolve(t.Name.Substring(0, t.Name.LastIndexOf("Controller")).ToLower()));
	}
 
	static IWindsorContainer GetContainer(string configuration)
	{
		// get path to configuration to test (inside the web site project)
		var path = ConfigFileRoot + Path.DirectorySeparatorChar 
				+ configuration + Path.DirectorySeparatorChar 
				+ "windsor.config";
 
		// configure Windsor
		var windsorContainer = new WindsorContainer(new XmlInterpreter(path));
 
		return windsorContainer;
	}
 
	static List<Type> GetControllerTypes()
	{
		// get assembly with controllers
		var assembly = Assembly.GetAssembly(typeof (HomeController));
 
		var types = assembly.GetTypes();
 
		// get all controller types
		return new List<Type>(types)
			.FindAll(t => typeof (IController).IsAssignableFrom(t)
			              && !t.IsAbstract);
	}
}

This way, if I introduce a service in my development configuration that should have been implemented by a production version of the service in my production configuration, I will immediately know about it.

I think this post covers an easy and pragmatic way to control multiple configurations with Windsor and ASP.NET MVC. Of course you might want to split out the configuration-specific parts into multiple files instead of having only a windsor.config for each configuration. What I mean is something like this:

<castle>
  <include uri="file://controllers-common.config"/>
  <include uri="file://controllers.config"/>
 
  <include uri="file://facilities-common.config"/>
  <include uri="file://facilities.config"/>
 
  <include uri="file://factories-common.config"/>
  <include uri="file://factories.config"/>
 
  <include uri="file://repositories-common.config"/>
  <include uri="file://repositories.config"/>
 
  <include uri="file://services-common.config"/>
  <include uri="file://services.config"/>
</castle>

The great thing is that we can refactor our configuration with confidence because of our test. And if we want to be extra-certain that everything works as expect, we might begin to add assertions like this:

public class TestWindsorCanResolve
{
	// (...)
 
	[Test]
	public void OnlyProductionEnvironmentCanSpamOurSensitiveClients()
	{
		Assert.IsTrue(GetContainer("development").Resolve<IEmailSender>() is FakeLoggingEmailSender);
		Assert.IsTrue(GetContainer("test").Resolve<IEmailSender>() is FakeLoggingEmailSender);
	}

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.

[this post is outdated - too much has happened since the first CTP]

In this part of the ASP.NET MVC tutorial we will create our own controller factory which will use Windsor to resolve dependencies and supply each controller with a NHaml view factory. Then we will create some simple views and watch the whole thing in the web browser.
Continue reading »

[this post is outdated - too much has happened since the first CTP]

This is the first post in a series of at least four about ASP.NET MVC, which I am planning. The series will show a way to build a nifty web site with a tidy, sound, and scalable architecture. ASP.NET MVC will be used to structure the web site, Castle ActiveRecord will be used for persistence, Castle Windsor for dependency injection, NUnit and NMock for testing, NHaml for the views, and principles from agile, domain-driven design, and test-driven development will be used. The series assumes that you want to use the model-view-controller pattern, so I will not try to convince you that it is a great way to structure a web site :-) – even though it is, and currently in my opinion the only sane way to make websites when they contain more than one page…

ASP.NET MVC is a part of the ASP.NET 3.5 Extensions, which is currently only available as a preview. Thus, the details might turn out to be a little off, but still most of the stuff we go through here will apply.

As this is the first post in the series, we will start out by creating a the solution and the project structure – just to get going.
Continue reading »

A great pattern in software architecture is dependency injection (DI). It is a classical pattern apparently, but it seems to have become very popular again in TDD circles because of its obvious positive impact on testability. Moreover, I believe it is a healthy architectural exercise to structure your code to support DI, because it enforces separation of concerns.

Dependency injection can be explained like this: if X requires a Y to do its work, X does not create the Y by itself, it is given a Y to use. Thus, DI is an example of inversion of control (IoC), which is a fancy term for whenever you pass something for someone to call functions on.

In the following post, I will give a short example on how to practice DI using the Windsor IoC container.
Continue reading »

© 2010 mookid on code Suffusion WordPress theme by Sayontan Sinha