Category Archives: ioc

Domain events salvation example

One of the immensely awesome things that Udi Dahan has – if not invented, then at least brought to my attention – is the awesome “domain events – salvation” pattern.

If you’re familiar with the onion architecture, you’ve probably more than once experienced the feeling that you had the need to pull something from your IoC container some place deep in your domain model. In my experience, that often happens when you have a requirement on the form “when something happens bla bla, then some other thing must happen bla bla” where “something” and “some other thing” aren’t otherwise related.

An example could be when a new account (a.k.a. a customer that we mean to do business with) is registered in the system, we should make sure that our credit assessment of the account is fresh enough that we dare do the businesss.

I’ve found that the “domain events – salvation” provides a solution to that problem. Check this out:

public class Account
{
    public void Register()
    {
        // ... do stuff that marks this account as registered
 
        DomainEvents.Raise(new AccountRegistered(this));
    }
}

“Whoa, what was that?” you might ask… that was a domain object that did some stuff, and in the end it raised a “domain event”, telling to the world what just happened. And yes, that was a domain object calling out to some static nastiness – but I promise you, it isn’t as nasty as you may think.

I’d like to assure you that the Account class is fully unit testable – i.e. it can be tested in isolation, just like we want. And that’s because we can abstract the actual handling of the domain events out behind an interface, IHandleDomainEvents, which is what actually gets to take care of the domain events – something like this:

public class DomainEvents
{
    public static IHandleDomainEvents Current = new DevNullDomainEventsHandler();
 
    public static void Raise(T domainEvent)
    {
        Current.Handle(domainEvent);
    }
}

and then IHandleDomainEvents can be implemented in several flavors and “injected” into the domain as a static dependency, e.g. this bad boy for testing:

public class TestDomainEventsHandlers : IHandleDomainEvents
{
    readonly List raisedDomainEvents = new List();
 
    public IEnumerable RaisedDomainEvents { get { return raisedDomainEvents; } }
 
    public voic Handle(T domainEvent)
    {
        raisedDomainEvents.Add(domainEvent);
    }
}

which can be used by installing a new instance of it in the setup phase of each test, and then running assertions against the collected domain events in the assert phase.

The coolest part though, is the production implementation of IHandleDomainEvents – it may look like this:

public class CastleWindsorDomainEventDispatcher : IHandleDomainEvents
{
    readonly IWindsorContainer container;
 
    public CastleWindsorDomainEventDispatcher(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public void Handle(T domainEvent)
    {
        var subscribers = container.ResolveAll<ISubscribeTo<T>>().ToList();
 
        try
        {
            subscribers.ForEach(s => s.Handle(domainEvent));
        }
        finally
        {
            subscribers.ForEach(s => container.Release(s));
        }
    }
}

thus delegating the handling of domain events to all implementors of ISubscribeTo<TDomainEvent>. This way, if I have registered this guy in my container:

public class EnsureCreditAssessmentIsFresh : ISubscribeTo<AccountRegistered>
{
    public EnsureCreditAssessmentIsFresh(ILookMaADependency lookMaADependency)
    {
        this.lookMaADependency = lookMaADependency;
    }
 
    public void Handle(AccountRegistered accountRegistered)
    {
        // possibly initiate new credit assessment in here...
    }
}

I can kick off a new credit assessment workflow when a new account is registered, and everything is wired together in a way that is semantically true to the domain. Also, my domain object suddenly get to pull stuff from the container (albeit in an indirect fashion), without even knowing about it!

Just a personal observation regarding the recent IoC debate on Twitter

Systems, where I’ve started out “as simple as possible”, and later wished that I had baked in an IoC container from the beginning: Several.

Systems, where I’ve baked in Castle Windsor from the beginning, and where I later wished that I hadn’t: 0.

#justsaying

(IMO, using an IoC container does not increase overall complexity – it just moves some of the complexity out of my code, and into a thing that implements a bunch of useful patterns in a slightly more opaque way than if I’d implemented those things myself.)

IoC component registration

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.

My favorite ASP.NET MVC hooks #1: Controller factory

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!

ASP.NET MVC – dependency injection by IoC container

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.

How to (really) implement your own ActionFilterAttribute

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?