Showing posts with label Windsor. Show all posts
Showing posts with label Windsor. Show all posts

Wednesday, October 27, 2010

RavenDb, ASP.NET MVC and Windsor working together

I’m putting together a new project, TardisBank.com, using RavenDb, ASP.NET MVC and Windsor. It’s up on github here:

http://github.com/mikehadlow/Suteki.TardisBank

Here’s how I wire up Windsor and RavenDb.

First, in Global.asax.cs I initialise the container and ask it to load and run installers from all the application assemblies:

public class MvcApplication : System.Web.HttpApplication, IContainerAccessor
{
    ...

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        InitialiseContainer();
        InitialiseControllerFactory();
    }

    protected void InitialiseContainer()
    {
        if (container == null)
        {
            container = new WindsorContainer()
                .Install(
                    FromAssembly.InDirectory(new AssemblyFilter(HttpRuntime.BinDirectory, "Suteki.*.dll")));
        }
    }

    protected void InitialiseControllerFactory()
    {
        var controllerFactory = container.Resolve<IControllerFactory>();
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    static IWindsorContainer container;
    public IWindsorContainer Container
    {
        get { return container; }
    }
}

One of the installers it runs is my RavenInstaller:

public class RavenInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IDocumentStore>().Instance(CreateDocumentStore()).LifeStyle.Singleton,
            Component.For<IDocumentSession>().UsingFactoryMethod(GetDocumentSesssion).LifeStyle.PerWebRequest
            );
    }

    static IDocumentStore CreateDocumentStore()
    {
        var store = new DocumentStore
        {
            ConnectionStringName = "tardisConnection"
        };
        store.Initialize();
        return store;
    }

    static IDocumentSession GetDocumentSesssion(IKernel kernel)
    {
        var store = kernel.Resolve<IDocumentStore>();
        return store.OpenSession();
    }
}

Because Windsor already provides a global application store for both singleton and per-request components, we can give it the responsibility of handling the instantiation and lifecycle of the DocumentStore and DocumentSesssion. The DocumentStore is created and initialised once the first time it is requested. The DocumentSession has a PerWebRequest lifestyle and is created using a factory method the first time it is requested.

Don’t forget to register the PerRequestLifestyleModule in Web.config:

<system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  
  <modules runAllManagedModulesForAllRequests="true">
    <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" />
  </modules>
</system.webServer>

Windsor will properly dispose both the DocumentStore when the application closes and the DocumentSession at the end of each request.

Monday, March 01, 2010

Thought experiment: The Curry Facility

Please indulge me for a while, I’ve been considering how to leverage the beauty of functional programming techniques and higher order functions but with the flexibility of an IoC container.

Imagine we have a couple of components that we want to register with our IoC container:

public class ComponentOne
{
    private readonly ComponentTwo componentTwo;

    public ComponentOne(ComponentTwo componentTwo)
    {
        this.componentTwo = componentTwo;
    }

    public SomeOutput SomeOperation(string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return componentTwo.SomeOperation(input);
    }
}

public class ComponentTwo
{
    public SomeOutput SomeOperation(SomeInput input)
    {
        return new SomeOutput {SomeOtherParameter = input.SomeParameter};
    }
}

Nothing unusual here. Now, ComponentTwo is simply a place to put the function SomeOperation, there’s no other need for it to exist. We could just as well supply a delegate to ComponentOne:

public class ComponentOne
{
    private readonly Func<SomeInput, SomeOutput> getInput;

    public ComponentOne(Func<SomeInput, SomeOutput> getInput)
    {
        this.getInput = getInput;
    }

    public SomeOutput SomeOperation(string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return getInput(input);
    }
}

public static class FunctionsTwo
{
    public static SomeOutput SomeOtherOperation(SomeInput input)
    {
        return new SomeOutput { SomeOtherParameter = input.SomeParameter };
    }
}

FunctionsTwo is just somewhere to put SomeOperation. Everything is static so we can consider it somewhat like a module or a namespace, it serves no other purpose.

We can already register this with Windsor like so:

var container = new WindsorContainer()
    .Register(
        Component.For<ComponentOne>(),
        Component.For<Func<SomeInput, SomeOutput>>().Instance(FunctionsTwo.SomeOtherOperation)
    );

var componentOne = container.Resolve<ComponentOne>();

var output = componentOne.SomeOperation("Hello World");

// writes "Hello World" to the console
Console.WriteLine(output.SomeOtherParameter);

But what about ComponentTwo, do we really need a class for our ‘SomeOperation’ method to live in? How about if we replace it with a higher order function:

public static class FunctionsOne
{
    public static SomeOutput SomeOperation(Func<SomeInput, SomeOutput> getInput, string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return getInput(input);
    }
}

Rather than providing the delegate as a private field of our class, that we expect to be passed as a constructor parameter, we simply provide it as the first argument of our SomeOperation method. It’s a classic example of a higher order function.

I’ve covered currying before, go and read my post on the subject if you haven’t encountered it. Languages like F# provide currying out of the box - thus F# functions only ever have one argument. You have to work a lot harder to make it work with with C#, but what if your IoC container could do the currying for you?

Now imagine we had a ‘CurryFacility’ so that we could do something like this:

var container = new WindsorContainer()
    .AddFacility<CurryFacility>()
    .Register(
        Component.For<Func<string, SomeOutput>>().SuppliedBy(FunctionsOne.SomeOperation),
        Component.For<Func<SomeInput, SomeOutput>>().SuppliedBy(FunctionsTwo.SomeOtherOperation)
    );

var getOutput = container.Resolve<Func<string, SomeOutput>>();

// writes "Hello World" to the console
Console.WriteLine(getOutput("Hello World"));

We’ve registered a service ‘Func<string, SomeOutput>’ but supplied a ‘Func<Func<SomeInput, SomeOuput>, string, SomeOutput>’. My imaginary CurryFacility would notice that to match the requested signature it would have to supply a delegate ‘Func<SomeInput, SomeOutput>’, which it would simply resolve as normal, and then partially apply SomeOperation to satisfy the service. I didn’t have time tonight to make it work, I but can’t see it being particularly painful to implement.

I’m very excited about the possibilities of functional programming, it allows us concisely describe problems without all the noise an OO language traditionally requires. In many cases a higher order function is a far more concise way of expressing the same thing as a class with DI’ed dependencies and a single method.

The CurryFacility doesn’t exist yet, but I’m going to have a go at putting something together. I’m not aware of anything like this existing already, but then I don’t follow the other .NET IoC containers. Let me know if someone’s already got an implementation.

Thursday, February 18, 2010

10 Advanced Windsor Tricks – 12. The NamingPartsSubsystem

Here’s part twelve of (slightly more than) 10 Advanced Windsor Tricks.

I’ve covered this before on this blog, but it was a while back and it’s such a neat trick that I don’t feel too bad about repeating myself. The NamingPartsSubsystem allows you to resolve components based on attributes. The attributes themselves are defined as part of the component’s name, so for example, we could have a component with a name like “thing:colour=red,version=2” and then resolve it by asking for a component with id “thing:colour=red”.

The name should match the following syntax:

<name>:<key 1>=<value 1>[,<key n>=<value n>]

Let’s say we define an interface and a number of classes that implement it:

private interface IThingy{}
private class Thing1 : IThingy {}
private class Thing2 : IThingy {}
private class Thing3 : IThingy {}
private class Thing4 : IThingy {}

Now we register them with various variations of the attributes ‘colour’ and ‘version’:

var container = new WindsorContainer();
container.Kernel.AddSubSystem(SubSystemConstants.NamingKey, new NamingPartsSubSystem());

container.Register(
        Component.For<IThingy>().ImplementedBy<Thing1>().Named("thing:colour=red,version=1"),
        Component.For<IThingy>().ImplementedBy<Thing2>().Named("thing:colour=blue,version=1"),
        Component.For<IThingy>().ImplementedBy<Thing3>().Named("thing:colour=red,version=2"),
        Component.For<IThingy>().ImplementedBy<Thing4>().Named("thing:colour=blue,version=2")
    );

Note the way we register the NamingPartsSubsystem.

OK, so now we have four different implementations of IThingy some red some blue, some version 1 and some version 2. Now if we just ask for a ‘thing’ we will get Thing1 since that was the first component named ‘thing:…’ that was registered:

var defaultThing = container.Resolve("thing");
Console.WriteLine("defaultThing = {0}", defaultThing.GetType().Name);

Outputs:
 
defaultThing = Thing1

If we ask for a red thing, we will still get Thing1 since that was the first red thing that was registered:

var redThing = container.Resolve("thing:colour=red");
Console.WriteLine("redThing.GetType().Name = {0}", redThing.GetType().Name);

Outputs:

redThing.GetType().Name = Thing1

If we ask for a blue thing we get Thing2 since that was the first blue thing that was registered:

var blueThing = container.Resolve("thing:colour=blue");
Console.Out.WriteLine("blueThing.GetType().Name = {0}", blueThing.GetType().Name);

Outputs:

blueThing.GetType().Name = Thing2

If we ask for a version 2 thing and we don’t care about the colour, we get Thing3, the first version 2 thing registered:

var version2 = container.Resolve("thing:version=2");
Console.Out.WriteLine("version2.GetType().Name = {0}", version2.GetType().Name);

Outputs:

version2.GetType().Name = Thing3

Finally if we ask for a version 2 blue thing, we get Thing4 since it’s the only thing that is both blue and version 4:

var blueThingVersion2 = container.Resolve("thing:colour=blue,version=2");
Console.Out.WriteLine("blueThingVersion2.GetType().Name = {0}", blueThingVersion2.GetType().Name);

Outputs:

blueThingVersion2.GetType().Name = Thing4

This is a very useful trick if you want to resolve components based on attributes that you configure them with. We’ll see a very neat use of this when we discuss IHandlerSelector next.

Tuesday, February 09, 2010

10 Advanced Windsor Tricks – 11. Type forwarding

Here’s part eleven of (slightly more than) 10 Advanced Windsor Tricks.

Have you noticed how I keep on putting off the WCF facility? It will come, I’m just waiting until I’ve got the time to do it justice. Instead, today’s trick is a nice easy one: type forwarding. This simply means that you can have a single component satisfy many services. As an example, say we have three interfaces:

public interface IThing
{
    string SayHello(string name);
}

public interface IWidget
{
    double Calculate(double a, double b);
}

public interface IWonder
{
    void DoesNothing();
}

Here’s a class called SrpViolator ;) It implements all three interfaces:

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

    public double Calculate(double a, double b)
    {
        return Math.Pow(a, b);
    }

    public void DoesNothing()
    {
        Console.WriteLine("Doing nothing");
    }
}

Type forwarding allows us to register all three interfaces as satisfied by SrpViolator:

var container = new WindsorContainer()
    .Register(
        Component
            .For<IThing>()
            .Forward<IWidget>()
            .Forward<IWonder>()
            .ImplementedBy<SrpViolator>()
    );

Update: Krzysztof Kozmic has pointed out that you can also simply have a comma separated list of interfaces in the ‘For’ clause for exactly the same effect:

var container = new WindsorContainer()
    .Register(
        Component
            .For<IThing, IWidget, IWonder>()
            .ImplementedBy<SrpViolator>()
    );

Now we can resolve each interface independently, but behind the scenes they are all share the same implementation:

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

var widget = container.Resolve<IWidget>();
Console.WriteLine("The answer is {0}", widget.Calculate(2, 3));

var wonder = container.Resolve<IWonder>();
wonder.DoesNothing();

Which outputs:

Hello Krzysztof from SrpViolator
The answer is 8
Doing nothing

Since SrpViolator is registered without specifying a lifestyle, it will have the default lifestyle: singleton. That means that ‘thing’, ‘widget’ and ‘wonder’ from the code snippet above are all the same instance of SrpViolator.

Type forwarding can be very useful, but note that the Single Responsibility Principle means that it’s generally considered bad practice to have a single class play many different roles.

Sunday, February 07, 2010

10 Advanced Windsor Tricks – 10. Configuration with type converters

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

This trick follows on nicely from trick number 9, ‘Configuring fluently registered components with XML’. Sometimes you might want a configuration value other than a simple string or integer. Windsor provides the ITypeConverter interface that you can implement to supply complex configuration for your components.

As an example, let’s imagine we have a class, HealthMonitor, that pings a series to endpoints and checks that a particular string is returned before a timeout. We want to configure HealthMonitor with an array of HealthEnpoints that specify a URL, an expected string value and a timeout in seconds. Something like this:

public interface IHealthMonitor
{
    HealthEndpoint[] HealthEndpoints { get; }
}

public class HealthMonitor : IHealthMonitor
{
    public HealthEndpoint[] HealthEndpoints { get; private set; }

    public HealthMonitor(HealthEndpoint[] healthEndpoints)
    {
        HealthEndpoints = healthEndpoints;
    }
}

public class HealthEndpoint
{
    public string Url { get; private set; }
    public string Expect { get; private set; }
    public int TimeoutSeconds { get; private set; }

    public HealthEndpoint(string url, string expect, int timeoutSeconds)
    {
        Url = url;
        Expect = expect;
        TimeoutSeconds = timeoutSeconds;
    }
}

I’ve left any implementation details out of HealthMonitor, it simply takes an array of HealthEndpoints that we can then inspect. We want our XML configuration to look something like this:

<component id="healthMonitor">
  <parameters>
    <healthEndpoints>
      <array>
        <item>
          <url>http://suteki.co.uk/ping</url>
          <expect>I am OK</expect>
          <timeoutSeconds>5</timeoutSeconds>
        </item>
        <item>
          <url>http://sutekishop.co.uk/ping</url>
          <expect>I am OK</expect>
          <timeoutSeconds>5</timeoutSeconds>
        </item>
        <item>
          <url>http://www.google.com</url>
          <expect>&lt;!doctype html&gt;</expect>
          <timeoutSeconds>1</timeoutSeconds>
        </item>
      </array>
    </healthEndpoints>
  </parameters>
</component>

Note that we want to use the standard Windsor configuration to say that the ‘healthEndpoints’ constructor parameter is made up of an array and each element of that array is described by ‘item’. We get that without doing anything special.

However, we do need some way of telling Windsor that when a component has a HealthMonitor dependency it should read a ‘url’, ‘expect’ and ‘timeoutSeconds’ value from the configuration and then construct a HealthEndpoint. We do that with a type converter.

Here’s our HealthEndpoint type converter:

public class HealthEndpointTypeConverter : AbstractTypeConverter
{
    public override bool CanHandleType(Type type)
    {
        return type == typeof (HealthEndpoint);
    }

    public override object PerformConversion(string value, Type targetType)
    {
        throw new NotImplementedException();
    }

    public override object PerformConversion(IConfiguration configuration, Type targetType)
    {
        var converter = new Converter(configuration.Children, Context);
        var url = converter.Get<string>("url");
        var expect = converter.Get<string>("expect");
        var timeoutSeconds = converter.Get<int>("timeoutSeconds");

        return new HealthEndpoint(url, expect, timeoutSeconds);
    }

    private class Converter
    {
        private readonly ConfigurationCollection configurationCollection;
        private readonly ITypeConverterContext context;

        public Converter(ConfigurationCollection configurationCollection, ITypeConverterContext context)
        {
            this.configurationCollection = configurationCollection;
            this.context = context;
        }

        public T Get<T>(string paramter)
        {
            var configuration =  configurationCollection.SingleOrDefault(c => c.Name == paramter);
            if (configuration == null)
            {
                throw new ApplicationException(string.Format(
                    "In the castle configuration, type '{0}' expects parameter '{1}' that was missing.",
                    typeof(T).Name, paramter));
            }
            return (T) context.Composition.PerformConversion(configuration, typeof (T));
        }
    }
}

We implement AbstractTypeConverter which provides us with some plumbing and implement three methods: ‘CanHandleType’ which tells Windsor which type(s) we are interested in; and two overloads of ‘PerformConversion’, one that takes a string and a target type and one that takes the current configuration section and a target type. Since we want to interpret the current configuration of each ‘item’ we’ll implement the second ‘PerformConversion’ method.

I’ve got a simple internal class ‘Converter’ that keeps track of child nodes of the ‘item’ node and the current context. It simply looks up each required property and converts it to a target type. Once we have our ‘url’, ‘expect’ and ‘timeoutSeconds’ values we construct and return a new HealthEndpoint. Note that we use Windsor’s built-in type converters for the simple target types: ‘context.Composition.PerformConversion’.

Wiring the type converter with Windsor is not obvious. You have to grab Windsor’s ConversionManager sub-system and add the new type converter to that. You could wrap that step with a facility, but there’s also a nice extension point, IWindsorInstaller, that you can also use to wrap up complex setup pieces:

public class HealthMonitorTypeConveterInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        var manager = (IConversionManager)container.Kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey);
        manager.Add(new HealthEndpointTypeConverter());
    }
}

Now we can bring it all together; installing our type converter and registering our HealthMonitor:

var container = new WindsorContainer()
    .Install(new HealthMonitorTypeConveterInstaller())
    .Install(Configuration.FromXmlFile("windsor.config"))
    .Register(
        Component.For<IHealthMonitor>().ImplementedBy<HealthMonitor>().Named("healthMonitor")
    );

If we resolve an IHealthMonitor and write out its enpoints like this:

var healthMonitor = container.Resolve<IHealthMonitor>();

foreach (var healthEndpoint in healthMonitor.HealthEndpoints)
{
    Console.Out.WriteLine("healthEndpoint.Url = {0}", healthEndpoint.Url);
    Console.Out.WriteLine("healthEndpoint.Expect = {0}", healthEndpoint.Expect);
    Console.Out.WriteLine("healthEndpoint.TimeoutSeconds = {0}", healthEndpoint.TimeoutSeconds);
}

We get this output on the console:

healthEndpoint.Url = http://suteki.co.uk/ping
healthEndpoint.Expect = I am OK
healthEndpoint.TimeoutSeconds = 5
healthEndpoint.Url = http://sutekishop.co.uk/ping
healthEndpoint.Expect = I am OK
healthEndpoint.TimeoutSeconds = 5
healthEndpoint.Url = http://www.google.com
healthEndpoint.Expect = <!doctype html>
healthEndpoint.TimeoutSeconds = 1

This is pretty simple example, but it’s possible to use type converters for some sophisticated configuration setups. Say you wanted to take some string value and parse it into a configuration class or maybe provide some kind of polymorphic configuration, all this can be done with a type converter.

OK, so that was trick 10, but don’t go away I’ve still got plenty more in the bag. Perhaps I should have used Scott Hanselman’s ‘… of an infinite series’ formula, but I quite like the fact that from now I’ll be over-delivering :)

Thursday, February 04, 2010

10 Advanced Windsor Tricks – 9. Configuring fluently registered components with XML

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

Did you know that you can mix fluent and XML configuration for the same component. I’m not the only one who thinks XML component registration is a verbose pit of failure. But there are some things you really do not want to hard code into your application. Things like connection strings, the location of resources on the network and other deployment specific settings. Windsor provides a very nice story for setting property values on your components using an XML file without having to fall back on the awful appSettings or defining your own custom ConfigurationSection. Here’s how it’s done:

Let’s say we have a class ConfigurationThing with some string properties for configuring a database connection:

public interface IConfigurationThing
{
    string Server { get; set; }
    string Database { get; set; }
    string User { get; set; }
    string Password { get; set; }
}

public class ConfigurationThing : IConfigurationThing
{
    public string Server { get; set; }
    public string Database { get; set; }
    public string User { get; set; }
    public string Password { get; set; }
}

We can fluently register it as normal:

var container = new WindsorContainer()
    .Install(Configuration.FromXmlFile("windsor.config"))
    .Register(
        Component
            .For<IConfigurationThing>()
            .ImplementedBy<ConfigurationThing>()
            .Named("configuration")
    );

Notice that we’re also including registration configuration from the file windsor.config. Also note that we give our IConfigurationThing service a name: ‘configuration’. Now in the windsor.config file we can configure the properties of ‘configuration’ by referencing it’s name – except that in the config file it’s confusingly called ‘id’:

<configuration>
  <components>
    <component id="configuration">
      <parameters>
        <Server>db.suteki.co.uk</Server>
        <Database>sutekishop</Database>
        <User>thingApp</User>
        <Password>1am_th3th1ng</Password>
      </parameters>
    </component>
  </components>
</configuration>

This is exactly the same as the standard XML component registration, except that we don’t specify the ‘service’ and ‘type’ attributes of the component. Windsor simply looks for a component registered with the same ‘id’… or rather ‘name’.

Now when we resolve our IConfigurationThing its properties are set to the values we specified in windsor.config:

var configuration = container.Resolve<IConfigurationThing>();

Console.Out.WriteLine("configuration.Server = {0}", configuration.Server);
Console.Out.WriteLine("configuration.Database = {0}", configuration.Database);
Console.Out.WriteLine("configuration.User = {0}", configuration.User);
Console.Out.WriteLine("configuration.Password = {0}", configuration.Password);

Which outputs:

configuration.Server = db.suteki.co.uk
configuration.Database = sutekishop
configuration.User = thingApp
configuration.Password = 1am_th3th1ng

Because Server, Database, User and Password are properties rather than constructor arguments, the component resolution will not fail if they are not supplied, instead they will all be null. This can be a nice feature if you want to supply default arguments that can be overridden by configuration.

I use this technique a lot. Configuration is one of those unexpected benefits of using Windsor.

Wednesday, February 03, 2010

10 Advanced Windsor Tricks – 8. Dependency graph visualisation

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

A frequent complaint people have when they first get to grips with IoC Containers is that they find it hard to tell how their application composes at runtime. What’s needed is a clear description of the tree of dependencies in your application. This dependency ‘graph’ is built at registration time and Windsor exposes its dependency graph via the GraphNodes collection on the Kernel. The following class recursively walks down the GraphNodes tree and outputs the application’s complete component graph:

using System;
using System.IO;
using Castle.Core;
using Castle.Windsor;

namespace Suteki.Common.Windsor
{
    public class DependencyGraphWriter
    {
        private readonly IWindsorContainer container;
        private TextWriter writer;

        public DependencyGraphWriter(IWindsorContainer container, TextWriter writer)
        {
            this.container = container;
            this.writer = writer;
        }

        public void Output()
        {
            var graphNodes = container.Kernel.GraphNodes;

            foreach (var graphNode in graphNodes)
            {
                if (graphNode.Dependers.Length != 0) continue;
                Console.WriteLine();
                WalkGraph(graphNode, 0);
            }
        }

        private void WalkGraph(IVertex node, int level)
        {
            var componentModel = node as ComponentModel;
            if (componentModel != null)
            {
                writer.WriteLine("{0}{1} -> {2}", 
                    new string('\t', level), 
                    componentModel.Service.FullName,
                    componentModel.Implementation.FullName);
            }

            foreach (var childNode in node.Adjacencies)
            {
                WalkGraph(childNode, level + 1);
            }
        }
    }
}

I usually have a test fixture that asserts various container registrations. Using the class above it’s easy to add a little explicit test that outputs the application’s graph:

[Test, Explicit]
public void Output_dependency_graph()
{
    var dependencyGraphWriter = new DependencyGraphWriter(container, Console.Out);
    dependencyGraphWriter.Output();
}

Here’s an small part of the output for Suteki Shop:

Suteki.Shop.Controllers.OrderStatusController -> Suteki.Shop.Controllers.OrderStatusController
    Suteki.Common.Repositories.IRepository`1 -> Suteki.Common.Repositories.Repository`1
        Suteki.Common.Repositories.IDataContextProvider -> Suteki.Common.Repositories.DataContextProvider
            Suteki.Common.Repositories.IConnectionStringProvider -> Suteki.Common.Repositories.ConnectionStringProvider
    Suteki.Shop.Services.IUserService -> Suteki.Shop.Services.UserService
        Suteki.Common.Repositories.IRepository`1 -> Suteki.Common.Repositories.Repository`1
            Suteki.Common.Repositories.IDataContextProvider -> Suteki.Common.Repositories.DataContextProvider
                Suteki.Common.Repositories.IConnectionStringProvider -> Suteki.Common.Repositories.ConnectionStringProvider
        Suteki.Shop.Services.IFormsAuthentication -> Suteki.Shop.Services.FormsAuthenticationWrapper
    Suteki.Shop.Services.IEmailService -> Suteki.Shop.Services.EmailService
        Suteki.Common.Services.IEmailBuilder -> Suteki.Common.Services.EmailBuilder
        Suteki.Common.Services.IEmailSender -> Suteki.Common.Services.EmailSenderLogger
            Suteki.Common.Services.IEmailSender -> Suteki.Common.Services.NullEmailSender
            Castle.Core.Logging.ILogger -> Castle.Services.Logging.Log4netIntegration.Log4netLogger
        Suteki.Shop.Services.IBaseControllerService -> Suteki.Shop.Services.BaseControllerService
            Suteki.Common.Repositories.IRepository`1 -> Suteki.Common.Repositories.Repository`1
                Suteki.Common.Repositories.IDataContextProvider -> Suteki.Common.Repositories.DataContextProvider
                    Suteki.Common.Repositories.IConnectionStringProvider -> Suteki.Common.Repositories.ConnectionStringProvider

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 :)