Friday, January 29, 2010

My DDD8 Talk: An Introduction to IoC Containers with Castle Windsor

Here are the slides for my DDD8 talk: An Introduction to IoC Containers with Castle Windsor.
http://static.mikehadlow.com/IntroductionToIocTalk/MikeHadlow_WhyDoINeedAnIoCContainer.pptx

Here are my notes.
http://static.mikehadlow.com/IntroductionToIocTalk/Code_Instructions.txt

And you can get the code my SutekiCode Google Code project here:
http://code.google.com/p/sutekicode/

I’m really looking forward to seeing you all in Reading. Come and say hello if you see me.

Wednesday, January 27, 2010

Configuring SmtpClient to drop emails in a folder on disk

Did you know that you can configure the built-in System.Net.Mail.SmtpClient to drop emails into a location on disk? This means that you don’t need an SMTP server for testing the email sending capabilities of your application.

You can find this advice in numerous places on the interweb, but I need to make a note here because every time I want to do it, I can’t remember the details and have to waste time browsing for it.

Simply put this configuration section in your App.config or Web.config file:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="SpecifiedPickupDirectory">
      <specifiedPickupDirectory pickupDirectoryLocation="c:\temp\maildrop\"/>
    </smtp>
  </mailSettings>
</system.net>

Now when you have some code like this:

var smtpClient = new SmtpClient();
var message = new MailMessage("no-reply@suteki.co.uk", "mike@suteki.co.uk")
{
    Subject = "The subject",
    Body = "The body of the message"
};
smtpClient.Send(message);

You get a file deposited in C:\temp\maildrop called something like ec40a365-270f-49ac-9aa5-1e68ec6a4df1.eml that looks like this:

X-Sender: no-reply@suteki.co.uk
X-Receiver: mike@suteki.co.uk
MIME-Version: 1.0
From: no-reply@suteki.co.uk
To: mike@suteki.co.uk
Date: 27 Jan 2010 21:32:05 +0000
Subject: The subject
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable

The body of the message

Sweet!

Tuesday, January 26, 2010

Brighton ALT.NET Beers – 2nd February at The Skiff

The next Brighton ALT.NET Beers will be held at the co-working venue ‘The Skiff’ at 7.00 pm on Tuesday 2nd of February. I’m taking over from Iain Holder for this one, since he’s just started a new job in the city and won’t be able to join us until later.

The address is: The Skiff, 49 Cheltenham Place, Brighton, BN1 4AB

The format will be the same as usual, a quick round of suggestions for topics, voting and then an evening of beer and geekery. Yes, that’s right, the Skiff are happy for us to bring along a crate of beers… those nice people :) There’s also a projector, so feel free to bring a laptop if there’s anything code related that you want to share.

See you there!

Tuesday, January 19, 2010

10 Advanced Windsor Tricks – 7. How to Write a Facility

Here’s part seven of (at least) 10 Advanced Windsor Tricks.

Facilities are Windsor’s main extension method. Pretty much all the bolt-on functionality that Windsor supports is via facilities and we’ve already seen a few in previous tricks. Facilities are easy to write, they basically just give you an opportunity to do some additional configuration and registration and the MicroKernel is extensible enough to support some very sophisticated scenarios.

For my example I want to take an idea I broached in the previous trick, a convention based event wiring facility. But first, in order to write a convention based event wiring facility I need some conventions:

  1. Events have strongly typed signatures, so no EventHandler. This facility is not designed for wiring up button click events, but is instead designed for strongly typed message publishing.
  2. A subscriber announces, via configuration, that it’s interested in a particular event type. The facility will wire it up to any event of the given type.
  3. A publisher should not have to have any special configuration. Simply having a public event will allow the facility to match it to subscribers.

Let’s start our facility. We can call it ‘EventSubscriptionFacility’. To act as a facility it has to implement IFacility:

public class EventSubscriptionFacility : IFacility
{
    public void Init(IKernel kernel, IConfiguration facilityConfig)
    {
        throw new NotImplementedException();
    }

    public void Terminate()
    {
        throw new NotImplementedException();
    }
}

A facility simply gives you a chance to do whatever registration work you need in its ‘Init’ method with the given kernel and configuration. We’ll see later how we can hook up to various kernel events to implement the functionality we need.

But before we start work on our facility, let’s write a test for it. First we need a subscriber and a publisher:

public class TypedMessagePublisher : IStartable
{
    public event Action<NewCustomerEvent> NewCustomer;

    public void CreateNewCustomer(string name, int age)
    {
        if (NewCustomer != null)
        {
            NewCustomer(new NewCustomerEvent { Name = name, Age = age });
        }
    }

    public void Start(){}
    public void Stop(){}
}

public class NewCustomerSubscriber
{
    public bool NewCustomerHandled { get; private set; }
    public string CustomerName { get; private set; }
    public int CustomerAge { get; private set; }

    public void Handle(NewCustomerEvent newCustomerEvent)
    {
        NewCustomerHandled = true;
        CustomerName = newCustomerEvent.Name;
        CustomerAge = newCustomerEvent.Age;
    }
}

public class NewCustomerEvent
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Our publisher publishes an event Action<NewCustomerEvent> which we want our subcriber to subscribe to. As in the previous trick, we make our publisher implement IStartable so that it get resolved for the first time during registration. Here’s a test to exercise our new facility:

var container = new WindsorContainer()
    .AddFacility<StartableFacility>()
    .AddFacility<EventSubscriptionFacility>()
    .Register(
        Component.For<TypedMessagePublisher>(),
        Component.For<NewCustomerSubscriber>()
            .SubscribesTo().Event<Action<NewCustomerEvent>>().WithMethod(s => s.Handle)
    );

var subscriber = container.Resolve<NewCustomerSubscriber>();
Assert.That(!subscriber.NewCustomerWasHandled);

var publisher = container.Resolve<TypedMessagePublisher>();
publisher.CreateNewCustomer("Sim", 42);

Assert.That(subscriber.NewCustomerWasHandled, "NewCustomerEvent was not handled");
Assert.That(subscriber.CustomerName, Is.EqualTo("Sim"));
Assert.That(subscriber.CustomerAge, Is.EqualTo(42));

As you can see there’s nothing explicitly linking the subscriber to the publisher. The publisher needs no extra configuration and the subscriber is merely configured to describe the event type it cares about and which method it wants to use to handle it.

Here’s the fluent API that allows us to do the subscription. It’s pretty standard stuff and mostly just generic type wrangling noise:

public static class EventSubscriptionFacilityConfigurationExtensions
{
    public static SubscriptionRegistration<TComponent> SubscribesTo<TComponent>(
        this ComponentRegistration<TComponent> registration)
    {
        return new SubscriptionRegistration<TComponent>(registration);
    }
}

public class SubscriptionRegistration<TComponent>
{
    private readonly ComponentRegistration<TComponent> componentRegistration;

    public SubscriptionRegistration(ComponentRegistration<TComponent> componentRegistration)
    {
        this.componentRegistration = componentRegistration;
    }

    public SubscriptionRegistrationForMethod<TComponent, TEvent> Event<TEvent>()
    {
        return new SubscriptionRegistrationForMethod<TComponent, TEvent>(componentRegistration);
    }
}

public class SubscriptionRegistrationForMethod<TComponent, TEvent>
{
    private readonly ComponentRegistration<TComponent> componentRegistration;

    public SubscriptionRegistrationForMethod(ComponentRegistration<TComponent> componentRegistration)
    {
        this.componentRegistration = componentRegistration;
    }

    public ComponentRegistration<TComponent> WithMethod(Func<TComponent, TEvent> handlerProvider)
    {
        componentRegistration.ExtendedProperties(Property
            .ForKey(EventSubscriptionFacility.SubscriptionPropertyKey)
            .Eq(new EventSubscriptionFacilityConfig(typeof(TEvent), handlerProvider)));
        return componentRegistration;
    }
}

public class EventSubscriptionFacilityConfig
{
    public Type EventType { get; private set; }
    public Delegate HandlerProvider { get; private set; }

    public EventSubscriptionFacilityConfig(Type eventType, Delegate handlerProvider)
    {
        EventType = eventType;
        HandlerProvider = handlerProvider;
    }
}

The neatest trick here is the ‘WithMethod’ method that allows us to grab a delegate function that takes an instance of our subscriber and returns an event handler delegate. We store that function and the event type in an extended property of the componentRegistration. Extended properties are very useful when we want to configure a registration in some way and then retrieve later in a facility.

Now to the facility itself. The core trick here is simply to attach handlers to the kernel’s ComponentModelCreated  and ComponentCreated events. ComponentModelCreated is fired when the configuration is consumed by the container and the model the container uses for each component is created. This is where we find our subscribers and extract the configuration we stored earlier. That configuration is saved in a dictionary.

The ComponentCreated event is triggered when an instance of a component is created. This usually happens on the first ‘Resolve’ call for a singleton, but in our case our publishers are marked with IStartable so they will be created during registration. Here we find any component that implements an event and then lookup any subscribers than have registered to handle that event. Then it’s a simple matter of getting the handler using the function we stored earlier and registering it with the event.

public class EventSubscriptionFacility : IFacility
{
    public const string SubscriptionPropertyKey = "__event_subscription__";
    private readonly IDictionary<Type, EventSubscriptionInfo> subscriptionConfigs = 
        new Dictionary<Type, EventSubscriptionInfo>();
    private IKernel kernel;

    public void Init(IKernel kernel, IConfiguration facilityConfig)
    {
        this.kernel = kernel;
        kernel.ComponentModelCreated += KernelOnComponentModelCreated;
        kernel.ComponentCreated += KernelOnComponentCreated;
    }

    private void KernelOnComponentModelCreated(ComponentModel model)
    {
        if(model.ExtendedProperties.Contains(SubscriptionPropertyKey))
        {
            var subscriptionConfig = (EventSubscriptionFacilityConfig)
                model.ExtendedProperties[SubscriptionPropertyKey];
            subscriptionConfigs.Add(subscriptionConfig.EventType, 
                new EventSubscriptionInfo(model.Name, model.Service, subscriptionConfig.HandlerProvider));
        }
    }

    private void KernelOnComponentCreated(ComponentModel model, object instance)
    {
        foreach (var eventInfo in model.Implementation.GetEvents())
        {
            if (subscriptionConfigs.ContainsKey(eventInfo.EventHandlerType))
            {
                var eventSubscriptionInfo = subscriptionConfigs[eventInfo.EventHandlerType];
                var subscriber = kernel.Resolve(
                    eventSubscriptionInfo.ComponentId, 
                    eventSubscriptionInfo.ServiceType);

                var handler = (Delegate)eventSubscriptionInfo.HandlerProvider.DynamicInvoke(subscriber);
                eventInfo.AddEventHandler(instance, handler);
            }
        }
    }

    public void Terminate()
    {
    }
}

public class EventSubscriptionInfo
{
    public string ComponentId { get; private set; }
    public Type ServiceType { get; private set;  }
    public Delegate HandlerProvider { get; private set; }

    public EventSubscriptionInfo(string componentId, Type serviceType, Delegate handlerProvider)
    {
        ComponentId = componentId;
        ServiceType = serviceType;
        HandlerProvider = handlerProvider;
    }
}

Now our test will pass.

It’s a limited first attempt, please don’t copy it and use in production. For example, it won’t work if a component has multiple subscriptions, or indeed if multiple subscribers are interested in the same event type, but I’m sure it would only take a little more effort to correct that.

The patterns I’ve shown here are pretty standard configuration and facility patterns that you see repeated throughout the Windsor code base. You can use a facility to something as simple as configuring a few components that you need to repeatedly register in multiple projects, or something as complex as the WCF Facility that we’ll be looking at soon.

Sunday, January 17, 2010

10 Advanced Windsor Tricks – 6. The Event Wiring Facility

Here’s part six of (at least) 10 Advanced Windsor Tricks.

C# has had events from version 1.0. Events effectively implement the observer pattern (another classic from the Gang of Four book) by maintaining the publisher’s collection of subscribed observers for you. The Windsor event wiring facility lets you register subscribers for an event using Windsor configuration. It means you can leave the actual wiring up of subscriber delegates to publisher events, to the facility.

Let’s look at an example. First here’s a simple event publisher:

public class MessagePublisher : IStartable
{
    public event Action<string> MessagePublished;

    public void PublishMessage(string message)
    {
        if (MessagePublished != null)
        {
            MessagePublished(message);
        }
    }

    public void Start(){}
    public void Stop(){}
}

It has a single event ‘MessagePublished’ that simply publishes a string. It also implements IStartable which means it will be started as soon as possible during registration time. Implementing IStartable also means that the ‘Start’ method will be called, which is an excellent opportunity for a more complex publisher to do any initialisation. If you haven’t read my pervious trick ‘The Startable Facility’ I’ll wait now while you go and have a look :)

Any class that wishes to subscribe to ‘MessagePublished’ simply needs to supply a method that takes a single string argument and returns void. Here’s an example:

public class MessageListener
{
    public void OnMessagePublished(string message)
    {
        Console.WriteLine("MessageListener got message: '{0}'", message);
    }
}

If we weren’t interested in using an IoC container we would wire up the listener to the publisher by creating instances of each and using the += operator to do the subscription:

var publisher = new MessagePublisher();
var subscriber = new MessageListener();

publisher.MessagePublished += subscriber.OnMessagePublished;
publisher.MessagePublished += message => Console.WriteLine("Me too {0}", message);

publisher.PublishMessage("Hello World!");

I’ve also subscribed a simple lambda expression too, just to show that you can add as many subscribers as you wish. This example will print out:

MessageListener got message: 'Hello World!'
Me too Hello World!

Now let’s see how we would do the same thing with Windsor and the event wiring facility:

var container = new WindsorContainer()
    .AddFacility<EventWiringFacility>()
    .Register(
        Component.For<MessagePublisher>()
            .Configuration(
                Child.ForName("subscribers").Eq(
                    Child.ForName("subscriber").Eq(
                        Attrib.ForName("id").Eq("messageListener"),
                        Attrib.ForName("event").Eq("MessagePublished"),
                        Attrib.ForName("handler").Eq("OnMessagePublished")
                        )
                    )
                ),
        Component.For<MessageListener>().Named("messageListener")
    );


var publisher = container.Resolve<MessagePublisher>();
publisher.PublishMessage("Hello World!");

First we add the EventWiringFacility itself, then we register the publisher and subscriber. The core thing to get right is the configuration of the publisher. The EventWiringFacility looks for any component with a child configuration element of ‘subscribers’ and then adds it to its list of publishers. When the publisher instance is created the facility loops through its subscribers collection, resolves each in turn and wires up the configured events to the configured handlers. The ultimate effect of this code is exactly like the non-container code above (excepting the lambda registration of course), with the MessageListener’s OnMessagePublished method subscribed to MessagePublisher’s MessagePublished event.

Note that making a component a subscriber of a publishing component is effectively the same as making it a dependency. A subscriber instance will be resolved (and created if it’s not an already existing singleton) when the publisher is created and will live as long as the publisher. Remember that in the example above, the publisher implements IStartable which means that was created before it was resolved and we are simply grabbing the existing instance so that we can call PublishMessage on it.

OK, so we can all agree the configuration is pretty ugly and could do with some fluent registration love. Colin Ramsay has an interesting blog post where he shows a fluent interpretation of the configuration. You’d probably want to do something similar if you are planning to be a heavy user of the EventWiringFacility.

For myself I’d like to see something a little more convention based. It would be easy for a facility to record any component with a public event and also record the event delegate type. Then any subscribers could simply announce that they wanted to subscribe to event type x with method y. It could include an optional event name to disambiguate all those EventHandler(object o, EventArgs e) events.

Saturday, January 16, 2010

10 Advanced Windsor Tricks – 5. The Startable Facility

Here’s part five of (at least) 10 Advanced Windsor Tricks.

Sometimes you may want a service instance to last the lifetime of your application. You might, for example, need to have a file watcher or maybe a service publishing events. We’ll see a good example of the later when we look at registering events on components. You could of course simply resolve a singleton instance when your application starts and call any start code on it, but there is a more elegant way of achieving the same goal: the Startable Facility.

The startable facility simply hooks into the ComponentModelCreated and ComponentRegistered events on the Kernel, looks for any component marked as startable, and then creates an instance and calls a start method as soon as all its dependencies can be resolved. It’s in the Castle.MicroKernel assembly, so you don’t have to add any new references to your project to use it.

You have two options to mark a component as startable, either have your component implement IStartable, or use configuration. The interface option doesn’t require any further configuration, but the second option allows you to start up components from 3rd parties and also allows you to keeps your classes free of Windsor dependencies.

Let’s look at an interface based startable component first. IStartable looks like this:

public interface IStartable
{
    void Start();
    void Stop();
}

Here’s a startable component called StartableThing:

public class StartableThing : IThing, IStartable
{
    public void Start()
    {
        Console.WriteLine("Starting");
    }

    public void Stop()
    {
        Console.WriteLine("Stopping");
    }

    public string SayHello(string name)
    {
        return string.Format("Hello, {0}, from StartableThing", name);
    }
}

To use StartableThing, simply register it like any other component. Note that we’ve also added the StartableFacility:

var container = new WindsorContainer()
    .AddFacility<StartableFacility>()
    .Register(
        Component.For<IThing>().ImplementedBy<StartableThing>()
    );

Console.WriteLine("After container registration, before resolving IThing");

var thing = container.Resolve<IThing>();
Console.WriteLine(thing.SayHello("Jack"));

container.Dispose();

This code will print out:

Starting
After container registration, before resolving IThing
Hello, Jack, from StartableThing
Stopping

As you can see, the component starts up at registration. It’s also worth noting that the ‘Start’ method is called in-process with the container registration, so you need to be careful not to block for long periods. Typically you would configure a startable component as singleton which means that at any point you can resolve it and examine or alter its state. Its ‘Stop’ method is called when the container is disposed.

Let’s have a look at a non-interface startable now. I’ve unimaginatively called it ‘NonInterfaceStartableThing’:

public class NonInterfaceStartableThing : IThing
{
    public void SomeStartMethod()
    {
        Console.WriteLine("Starting");
    }

    public void SomeStopMethod()
    {
        Console.WriteLine("Stopping");
    }

    public string SayHello(string name)
    {
        return string.Format("Hello, {0}, from NonInterfaceStartableThing", name);
    }
}

Note that this class does not implement IStartable, instead we have to explicitly tell the startable facility what the start and stop methods are. The registration looks like this:

var container = new WindsorContainer()
    .AddFacility<StartableFacility>()
    .Register(
        Component.For<IThing>().ImplementedBy<NonInterfaceStartableThing>()
            .StartUsingMethod("SomeStartMethod")
            .StopUsingMethod("SomeStopMethod")
    );

Console.WriteLine("After container registration, before resolving IThing");

var thing = container.Resolve<IThing>();
Console.WriteLine(thing.SayHello("Jack"));

container.Dispose();

This has the same output as the IStartable example above.

As you can see the Startable Facility is a very useful addition to your IoC toolbox.

Friday, January 15, 2010

10 Advanced Windsor Tricks – 4. How to register and use decorators

Here’s part four of (at least) 10 Advanced Windsor Tricks.

The decorator pattern is an old friend from the Gang of Four book and goes back to the earliest days of Object Oriented programming. It’s a very simple but powerful idea. Let’s remember our old friend ThingOne:

public class ThingOne : IThing
{
    public string SayHello(string name)
    {
        return string.Format("ThingOne says hello to {0}", name);
    }
}

A decorator is a class that both implements an interface and has a reference to it. This is so that it can pretend to be something else and intercept any calls made to the wrapped instance. Here’s an IThing decorator:

public class ThingDecorator : IThing
{
    private readonly IThing thing;

    public ThingDecorator(IThing thing)
    {
        this.thing = thing;
    }

    public string SayHello(string name)
    {
        Console.WriteLine("Before calling wrapped IThing");
        var message = thing.SayHello(name);
        Console.WriteLine("After calling wrapped IThing");
        return message;
    }
}

A decorator can do anything it likes before and after the call to the wrapped class including altering its arguments and/or return value. There is much discussion of AOP these days and heavyweight frameworks like PostSharp; indeed Windsor itself is an excellent AOP framework; but often a decorator is a much simpler solution to these kinds of interception requirements. Don’t get me wrong though, I think PostSharp is the bees knees :)

Now we can compose the decorator with the target and allow the decorator to intercept calls to the target:

var thing = new ThingDecorator(new ThingOne());
Console.WriteLine(thing.SayHello("Roger"));

Which will print out:

Before calling wrapped IThing
After calling wrapped IThing
ThingOne says hello to Roger

Windsor makes working with decorators a breeze. You don’t have to explicitly wire up the decorator with a service override, simply order the registrations with the outermost decorator first and Windsor will magically wire them up for you. So to register ThingDecorator and ThingOne just do the following:

var container = new WindsorContainer()
    .Register(
        Component.For<IThing>().ImplementedBy<ThingDecorator>(),
        Component.For<IThing>().ImplementedBy<ThingOne>()
    );

var thing = container.Resolve<IThing>();

Console.WriteLine(thing.SayHello("Roger"));

This prints out the same result as the code above.

Now, let’s introduce a second decorator:

public class ThingDecorator2 : IThing
{
    private readonly IThing thing;

    public ThingDecorator2(IThing thing)
    {
        this.thing = thing;
    }

    public string SayHello(string name)
    {
        return thing.SayHello(name + " has been altered by ThingDecorator2... ha ha ha!");
    }
}

When we register this decorator as well we get just the effect we expect:

public void decorator_should_work_without_any_special_registration()
{
    var container = new WindsorContainer()
        .Register(
            Component.For<IThing>().ImplementedBy<ThingDecorator>(),
            Component.For<IThing>().ImplementedBy<ThingDecorator2>(),
            Component.For<IThing>().ImplementedBy<ThingOne>()
        );

    var thing = container.Resolve<IThing>();

    Console.WriteLine(thing.SayHello("Roger"));
}

This prints out:

Before calling wrapped IThing
After calling wrapped IThing
ThingOne says hello to Roger has been altered by ThingDecorator2... ha ha ha!

It’s nice, in fact it’s cooler than a Shaft and Fonz love child :)

Wednesday, January 13, 2010

10 Advanced Windsor Tricks – 3. How to resolve arrays

Here’s part three of (at least) 10 Advanced Windsor Tricks.

By default Windsor will not resolve arrays. That is, if you have a number of components registered with the same service, resolving an array of that service will result in an error saying that it cannot satisfy the array dependency.

However there’s a simple solution. Windsor comes with an optional sub-dependency-resolver that can resolve arrays; the ArrayResolver. Here’s how you use it:

First let’s meet our old friends the Things:

public class ThingOne : IThing
{
    public string SayHello(string name)
    {
        return string.Format("ThingOne says hello to {0}", name);
    }
}

public class ThingTwo : IThing
{
    public string SayHello(string name)
    {
        return string.Format("ThingTwo says hello to {0}", name);
    }
}

public class ThingThree : IThing
{
    public string SayHello(string name)
    {
        return string.Format("Hello {0} from ThingThree", name);
    }
}

And here’s a class with a dependency on an array of IThing:

public class UsesThingArray
{
    public IThing[] Things { get; private set; }

    public UsesThingArray(IThing[] things)
    {
        Things = things;
    }
}

I like to wrap the ArrayResolver in a little facility (it would be nice if this was in Windsor), but you don’t have to do this:

public class ArrayFacility : IFacility
{
    public void Init(IKernel kernel, IConfiguration facilityConfig)
    {
        kernel.Resolver.AddSubResolver(new ArrayResolver(kernel));
    }

    public void Terminate(){ }
}

Now you can use fluent registration to register the ArrayFacility and components:

var container = new WindsorContainer()
    .AddFacility<ArrayFacility>()
    .Register(
        AllTypes
            .Of<IThing>()
            .FromAssembly(Assembly.GetExecutingAssembly())
            .WithService.FirstInterface(),
        Component.For<UsesThingArray>()
    );

And finally, this code now works with all three things having their ‘SayHello’ method executed:

var usesThingArray = container.Resolve<UsesThingArray>();
foreach (var thing in usesThingArray.Things)
{
    Console.WriteLine(thing.SayHello("Leo"));
}

The nice thing about this is that if I want to add another element to the array, I simply create a new class that implements IThing which automatically gets registered and handed to UsesThingArray without a single change to any existing code. It’s craftier than a fox who has just graduated from Ruse University with a Degree in cunning!

There is a caveat; the ArrayResolver voids Windsor’s circular dependency detection. See my previous post on this for more detail.

Tuesday, January 12, 2010

10 Advanced Windsor Tricks – 1A. A Delegate Factory Facility

Here’s part 1A of my series: 10 Advanced Windsor Tricks.

Yes, I’m getting totally side-tracked already. After I published my first trick ‘Registering Delegates’ I got into a twitter conversation with Tuna Toksoz, who, if you don’t know already, is one of the Castle committers and a seriously hardcore when it comes to IoC containers :) Tuna got me thinking that it would be very simple to extend my delegate trick to create a facility to automatically return a factory for a registered type to any class with a dependency to Func<registered type>.

This isn’t an original idea, Autofac already has ‘auto generated factories’ that work in exactly this way.

Show me the code already. OK, say we have our ThingOne from before:

public class ThingOne : IThing
{
    public string SayHello(string name)
    {
        return string.Format("ThingOne says hello to {0}", name);
    }
}

And we also have a class, UsesThingFactory that has a dependency on Func<IThing>:

public class UsesThingFactory
{
    private readonly Func<IThing> thingFactory;

    public UsesThingFactory(Func<IThing> thingFactory)
    {
        this.thingFactory = thingFactory;
    }

    public IThing GetMeAThing()
    {
        return thingFactory();
    }
}

With my AutoFactoryFacility I don’t have to register Func<IThing>, just IThing and UsesThingFactory. The facility automatically creates the resolve delegate to hand to UsesThingFactory without any further action:

var container = new WindsorContainer()
    .AddFacility<AutoFactoryFacility>()
    .Register(
        Component.For<IThing>().ImplementedBy<ThingOne>(),
        Component.For<UsesThingFactory>()
    );

var usesThingFactory = container.Resolve<UsesThingFactory>();

Console.WriteLine(usesThingFactory.GetMeAThing().SayHello("Tuna"));
Console.WriteLine(usesThingFactory.GetMeAThing().SayHello("Tuna"));

The facility only took a few minutes to knock together using a sub dependency resolver:

public class AutoFactoryFacility : IFacility
{
    public void Init(IKernel kernel, IConfiguration facilityConfig)
    {
        kernel.Resolver.AddSubResolver(new AutoFactoryResolver(kernel));
    }

    public void Terminate(){}
}

public class AutoFactoryResolver : ISubDependencyResolver
{
    private readonly IKernel kernel;

    public AutoFactoryResolver(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public object Resolve(
        CreationContext context, 
        ISubDependencyResolver contextHandlerResolver, 
        ComponentModel model, 
        DependencyModel dependency)
    {
        var getResolveDelegateGeneric = GetType().GetMethod("GetResolveDelegate");
        var getResolveDelegateMethod = 
            getResolveDelegateGeneric.MakeGenericMethod(dependency.TargetType.GetGenericArguments()[0]);
        return getResolveDelegateMethod.Invoke(this, null);
    }

    public bool CanResolve(
        CreationContext context, 
        ISubDependencyResolver contextHandlerResolver, 
        ComponentModel model, 
        DependencyModel dependency)
    {
        return dependency.TargetType.IsGenericType 
            && (dependency.TargetType.GetGenericTypeDefinition() == typeof (Func<>))
            && (kernel.HasComponent(dependency.TargetType.GetGenericArguments()[0]));
    }

    public Func<T> GetResolveDelegate<T>()
    {
        return () => kernel.Resolve<T>();
    }
}

Far too much reflection voodoo for my liking. There must be a more elegant way of doing this, but I can’t see it. But in any case it works and gives me a really nice way of grabbing components as needed without any nasty dependencies on service locators or having to manually create factories.

A further refinement would be to add Func<string, T> so that you can resolve typed components by name.

Monday, January 11, 2010

10 Advanced Windsor Tricks – 2. Auto Registration

Here’s part two of (at least) 10 Advanced Windsor Tricks.

Today’s trick isn’t really ‘Advanced’, but it’s very cool none the less. Windsor now has a very nice fluent registration API that’s far easier to use than the old XML configuration (but don’t dismiss the XML config, it’s very useful for standard application configuration tasks as we’ll see in a later trick). With fluent configuration you can set up conventions for your application so that as you create new components you aren’t required to register them individually.

For this example, let’s say we have an interface IThing:

namespace Mike.AdvancedWindsorTricks.Model
{
    public interface IThing
    {
        string SayHello(string name);
    }
}

And two classes that implement IThing:

namespace Mike.AdvancedWindsorTricks.Model
{
    public class ThingOne : IThing
    {
        public string SayHello(string name)
        {
            return string.Format("ThingOne says hello to {0}", name);
        }
    }
}

namespace Mike.AdvancedWindsorTricks.Model
{
    public class ThingTwo : IThing
    {
        public string SayHello(string name)
        {
            return string.Format("ThingTwo says hello to {0}", name);
        }
    }
}

Our solution structure looks something like this:

AdvancedWindsorTricksModelSolution

First we can set things (ha!) up so that any class that implements IThing gets registered:

var container = new WindsorContainer()
    .Register(
        AllTypes
            .Of<IThing>()
            .FromAssembly(Assembly.GetExecutingAssembly())
            .Configure(component => component.LifeStyle.Transient)
    );

This will register both ThingOne and ThingTwo. Note that we can also configure our components as well. Here I’m making any implementation of IThing transient.

You can also ask Windsor to register all components in a particular namespace:

var container = new WindsorContainer()
    .Register(
        AllTypes
            .FromAssembly(Assembly.GetExecutingAssembly())
            .Where(Component.IsInNamespace("Mike.AdvancedWindsorTricks.Model"))
    );

This will also register ThingOne and ThingTwo and any other classes that have the namespace ‘Mike.AdvancedWindsorTricks.Model’.

Note that for both these examples, if you ask the container for an IThing, you will get an error saying that no component has been registered for IThing. Each component’s service is its own type by default. If you want the service to be IThing you have to specify ‘WithService.FirstInterface’ like this:

.Register(
    AllTypes
        .Of<IThing>()
        .FromAssembly(Assembly.GetExecutingAssembly())
        .Configure(component => component.LifeStyle.Transient)
        .WithService.FirstInterface()
 
We can ask Windsor to register components based on any arbitrary condition with the Where clause:
 
var container = new WindsorContainer()
    .Register(
        AllTypes
            .FromAssembly(Assembly.GetExecutingAssembly())
            .Where(t => t.GetInterfaces().Any())
    );

The Where clause takes a Predicate<Type>, so you can use any condition of the type to register the component. Here I’ve registered any types that have at least one interface.

Finally we can mix all the above in any combination we wish:

var container = new WindsorContainer()
    .Register(
        AllTypes
            .Of<IThing>()
            .FromAssembly(Assembly.GetExecutingAssembly())
            .Where(Component.IsInNamespace("Mike.AdvancedWindsorTricks.Model"))
            .Where(t => t.GetInterfaces().Any())
            .Configure(component => component.LifeStyle.Transient)
            .ConfigureFor<ThingTwo>(component => component.Named("thing.the.second"))
            .WithService.FirstInterface()
    );

Notice that we can also specify configuration for particular components. Here I’m setting the component name for ThingTwo as ‘thing.the.second’.

Auto registration can make development really slick. I usually have a namespace something like ‘Company.Project.Services’ and setup auto registration so that any class that implements a single interface gets registered with the interface as its service. When I want to add some new functionality, I simply a create a new service and service interface under that namespace, then consume it anywhere I like with dependency injection. It’s smoother than a cat :)

Sunday, January 10, 2010

10 Advanced Windsor Tricks – 1. Registering Delegates

Here’s part one of (at least) 10 Advanced Windsor Tricks.

Did you know that you can register delegates in Windsor? Here I’m just registering a Func<String> that returns “Hello World”

var container = new WindsorContainer()
    .Register(
        Component.For<Func<string>>().Instance(() => "Hello World")
    );

var sayHello = container.Resolve<Func<string>>();
Console.WriteLine(sayHello());

This will print out ‘Hello World’ on the console.

This has some pretty cool implications. For example, say you want to resolve different named instances of the same component at runtime. Without this trick you would have to reference the container itself, which is an IoC anti-pattern of epic proportions. Instead, just register a delegate that takes a string and returns your service type then supply container.Resolve<MyServiceType> as it’s instance. Confused? Here’s an example:

First two classes: Do and BigDo (smirk:)

public class Do
{
    public virtual void SayHello()
    {
        Console.WriteLine("Hello from Do");
    }
}

public class BigDo : Do
{
    public override void SayHello()
    {
        Console.WriteLine("Hello from BigDo");
    }
}

BigDo inherits Do and they both implement ‘SayHello’. Now here’s a class that depends on something of type ‘Do’, but doesn’t know which named ‘Do’ it wants until runtime:

public class UseDo
{
    private readonly Func<String, Do> doFactory;

    public UseDo(Func<String, Do> doFactory)
    {
        this.doFactory = doFactory;
    }

    public Do GetDo(string name)
    {
        return doFactory(name);
    }
}

It takes a delegate dependency Func<String, Do> which acts as a ‘Do Factory’. At runtime a client can call ‘GetDo’ to return the named ‘Do’ it wants. The container registration is very simple:

var container = new WindsorContainer();
container
    .Register(
        Component.For<Do>().Named("do1"),
        Component.For<Do>().ImplementedBy<BigDo>().Named("do2"),
        Component.For<Func<String,Do>>().Instance(container.Resolve<Do>),
        Component.For<UseDo>()
        );

First we register the two different implementations of ‘Do’ and give them both names. Next we register the factory delegate. We can simply pass the method cotainer.Resolve<Do> as the delegate instance because one of Resolve<Do>’s overrides takes a string argument and returns Do. Finally we register the client class ‘UseDo’.

Now we can call UseDo.GetDo and return different named versions of Do:

var useDo = container.Resolve<UseDo>();
var do1 = useDo.GetDo("do1");
var do2 = useDo.GetDo("do2");

do1.SayHello();
do2.SayHello();

Which prints out the following on the console:

Hello from Do
Hello from BigDo

You could use this same trick to resolve multiple named component configurations which I’ve seen a lot of recently (yes, you know who you are). One step on from here would be to have Func<T> automatically wired up to container.Resolve<T>() and Func<String, T> to container.Resolve<T>(name) a la Autofac. Hmm…..

10 Advanced Windsor Tricks - Introduction

I love speaking at the developer days held at Microsoft UK's Reading campus. The next one is going to be on the 30th January, so make sure you get in there quick when the registration opens on the 15th. Overreaching myself again, I've put forward three talks:

  • An Introduction to IoC Containers with Castle Windsor
  • Enterprise Integration with MassTransit
  • 10 Advanced Windsor tricks

I've presented the first two before, but the '10 Advanced Windsor tricks' is new. As a way of preparing I thought I would spend the next 10 days blogging about the 10 tricks that I plan to talk about.

update: I’ve just found out that my Introduction to IoC Containers talk has been accepted, but not 10 Advanced Windsor Tricks. Hopefully I’ll get to present it at some other forum in the near future. In any case, I’ll carry on with the blog posts.

Here's my list so far... which has more than 10 items... Hmm, I'll have to decide which ones to drop

- Registering Delegates  & A Delegate Factory Facility
- Auto registration
- How to resolve arrays
- How to register and use decorators
- The Startable Facility
- The EventWiring Facility
- How to write a Facility
- Dependency graph visualisation
- Configuring fluently registered components with XML
- Configuration with type converters
- Type Forwarding
- The NamingPartsSubsystem
- Use SubContainers to replace dependencies on context 
- Using IHandlerSelector for runtime component selection
- The WCF Facility
- How to use Sub Containers
- Lazy Loading
- Typed Factory Facility
- Interceptors

I’m committing the source code examples to my Suteki Code Google code project. You download and/or browse the samples from here:
http://code.google.com/p/sutekicode/source/browse/#svn/trunk/Samples/Mike.AdvancedWindsorTricks

I’ll wrap the code up in a convenient zip file once I’ve completed the series.