Showing posts with label SOLID. Show all posts
Showing posts with label SOLID. Show all posts

Monday, February 11, 2013

A Better Dispatcher with the Factory Facility

In the applications we write, we often use the same principles. First off, there is dependency injection, preferably through the constructor of a class. Second we often use CQS, to get a clear separation between the commands and queries of our application.

For implementing CQS we often utilize some kind of a dispatcher. This is a simple class which has Dispatch methods for commands and queries. We can use it like so:

public class DoubleAddressController : Controller
{
    readonly IDispatcher _dispatcher;

    public DoubleAddressController(IDispatcher dispatcher)
    {
        _dispatcher = dispatcher;
    }

    public ActionResult GetExistingFilesForAddress(FindDoubleAddressRequest request)
    {
        var result = _dispatcher.DispatchQuery<FindDoubleAddressRequest, FindDoubleAddressResponse>(request);
        return PartialView(result);
    }
}


We ask the dispatcher to dispatch a query for a certain request and response. I ommitted error handling and additional mapping from the above example.

So, the dispatcher gets a certain command or query as an argument and based on this needs to ask a certain query or commandhandler to handle this command or query. Up untill now I used the IoC repository to get hold of this queryhandler:

public class Dispatcher : IDispatcher
{
    readonly IWindsorContainer _windsorContainer;

    public Dispatcher(IWindsorContainer windsorContainer)
    {
        _windsorContainer = windsorContainer;
    }

    public TResponse DispatchQuery<TRequest, TResponse>(TRequest request)
    {
        var handler = _windsorContainer.Resolve<IQueryHandler<TRequest, TResponse>>();

        if (handler == null)
            throw new ArgumentException(string.Format("No handler found for handling {0} and {1}", typeof(TRequest).Name, typeof(TResponse).Name));

        try
        {
            return handler.Handle(request);
        }
        finally
        {
            _windsorContainer.Release(handler);
        }
    }
}

The dispatcher has a dependency on our IoC container, in the example above a WindsorContainer, and asks this container to get hold of the specific handler that can handle the request we just got in.

With this solution however there are a couple of problems. First of all, we need a dependency on our IoC container (in the IoC configuration we configure the container with a reference to itself). Second, we resolve a dependency from the container, which is just not done (service location is known as an anti-pattern). And we need to think about releasing the handler dependency we just resolved. Something the developer needs to think about and which I've seen forgotten.

So, there should be a better solution for this, and there is! I recently started a refactor on another piece of code which used a factory to get hold of instances and which did not make use of our Castle Windsor container. I started looking at the Castle Windsor documentation and you can actually configure it with classes which act as factory and with a factory facility. After this refactoring I thought this factory facility might as well be usable for our not so ideal dispatcher.

First we got rid of the WindsorContainer dependency in the dispatcher:

public class Dispatcher : IDispatcher
{
    private readonly IFindHandlersFactory _handlerFactory;

    public Dispatcher(IFindHandlersFactory handlerFactory)
    {
        _handlerFactory = handlerFactory;
    }

    public TResult Dispatch<TRequest, TResult>(TRequest request)
    {
        var handler = _handlerFactory.CreateFor<TRequest, TResult>(request);
        if (handler == null)
            throw new HandlerNotFoundException(typeof(IQueryHandler<TRequest, TResult>));
        
        return handler.Handle(request);
    }
}


We now use a IFindHandlersFactory. A factory which just finds handlers for us. This interface just has one method defined, CreateFor, with generic type parameters. The thing is that we will not make an implementation for this interface. This interface will be configured in our Castle Windsor container as a factory.


container.AddFacility<typedfactoryfacility>();

container
    .Register(
        Component
            .For<IDispatcher>()
            .ImplementedBy<Dispatcher>()
            .LifestyleTransient())
    .Register(
        Component
            .For<IHandlerFactory>()
            .AsFactory()
            .LifestyleTransient())
    ;

Once you have done this, Castle Windsor will automatically resolve your handlers, without you having to actually call Resolve for these dependencies.

Sunday, June 12, 2011

NDC 2011

Last week some colleagues and I went to the NDC conference in Norway.



Apart from the weather, which was crappy, it was an awesome conference. I've seen some great talks and am looking forward to watching some of the talks I missed (because I was in another session) online. I also went home with some new great ideas for books I want to read:

  • Introducing HTML 5, by Bruce Lawson and Remy Sharp. They gave the HTML 5 talks during the second day of the conference in a small and very crowded room. They convinced me even more of the amazing things you can do for web pages with the new upcoming standard. It was a relieve as well to hear someone from the Opera browser team talking about HTML 5 instead of the standard Microsoft talks I heard thus far. 
  • Test-Driven JavaScript Development, by Christian Johansen. Too bad his talk was given simultaneously with Rob Ashton's (Document databases with ASP.NET MVC), Kevlin Henney and Anders NorĂ¥s's (Introducing The FLUID Principles) and Hadi Hariri's (Dynamic in a Static World). I went to this last session, which was very good. It gave me some ideas and examples of more things I can start doing with dynamic. I would really like to try to get a DSL written with it (I would probably start off by copying a Ruby example, since it is not easy stuff). The talk about the FLUID principles was very good as well, my colleagues went to that one and it is one of the talks to catch on rerun, once they put the videos up. I did follow the talk about the SOLID principles, which was nice to refresh again. I went to the RavenDB by Example talk on day  3 of the conference. It was a good thing the speaker also mentioned some of the problems he had with a document database, having to rethink the design of your data as opposed to relational databases.
  • The Joy of Closure, by Michael Fogus and Chris Houser. I didn't get to catch any of the Closure and F# talks and it would be nice to get up to speed with this. Also something to watch on rerun and see what we can do with it
  • 97 Things Every Programmer Should Know, by Kevlin Henney and 97 Things Every Software Architect Should Know, by Richard Monson-Haefel. I only went to Kevlin's talk about the 101 things he learned in architecture school, which was light, but enlighting. His other two talks apparently were very good as well, as my colleague went to those.
  • Specification By Example, by Gojko Adzic. His talk wasn't so good, but I think a lot can be learned from this book. One thing I will really remember from the conference is the multiple question marks that speakers had with BDD, DDD and agile. While they are all good techniques, they have their flaws and the software community really needs to figure out how we can do these things even better. Gojko's post on his blog about one of these talks really explains the problem a bit as well. He also mentioned our Cronos colleagues from iLean in his talk, which I think was pretty cool. And he is also one of the creators of cuke4ninja, a port of cucumber for .Net.


Apart from those books and talks I already mentioned, I also followed some of the talks on mobile development. The ones about multi platform development were really informative. The MonoTouch and MonoDroid projects have moved from Novell to Xamarin and are planning on a next release in the coming months. Biggest take-away there was: use the latest MonoTouch and MonoDroid builds for now and switch to the Xamarin builds once they are published. Jonas Follesoe's talk on this topic was great, if you're doing mobile, catch it on rerun! 

I also really liked the AOP talks given by the PostSharp people. They have a great framework for doing AOP, which is really powerfull and which gives you a lot of cool features for keeping your code nice and, well, sharp. They also mentioned some other AOP frameworks, which I think is a nice gesture, since they are not the only ones out there.

The CQRS talk by Fredrik Kalseth was inspiring as well, although he only mentioned one part of CQRS. It was explained really well and can be used as a basis on future projects. I also learned in his talk that JetBrains have a Ruby IDE which I didn't know about. As I look at their site now, I see they're also working on an Objective-C IDE. 



So, all in all, a very good conference, which I hope to catch again next year, and hopefully without the rain. I learned a lot and have now a whole lot of stuff to read and learn even more about. Too bad there's only 24 hours in a day (of which I really need 9 to sleep, since I'm a sleepy head).

Thanks as well to my colleague, Guy, for providing some very nice pictures. You can find the entire collection here.