Castle Windsor and child containers: Revolutions

Continuing the topic from the previous posts.

What would happen?

Current behavior of Windsor is somewhat flawed. What it will do is it will resolve foo, and provide it with bar. The flaw of this behavior is that now when we resolve foo via any of the tree containers we’ll  get the same instance (since it’s a singleton). This introduced two issues:

  • component from childA (bar) will now be available via childB and parent while logically thinking – it should not.
  • we have temporal coupling in our code. Depending on the order of containers we’ll use to resolve foo we’ll get different results

So what should happen?

Ok, so now that we agreed that current behavior is indeed flawed (we did, didn’t we?) what are our options for fixing it? We basically have two options (both of which were mentioned in comments to previous post).

It all boils down to scoping. If we have a per-web-request object – should single instance be shared among multiple containers or should it be per-web-request-and-per-container? If we have singleton should it be single instance per container, per container hierarchy or per process?

Let’s consider slightly more complicated picture.

containers_2

Now we have two components for bar, one in childA and one in parent. Also we have one more component; baz, which is registered in childB.

classes_2

Baz has dependency on foo, foo still has dependency on bar. All of these dependencies are optional, and all components are singletons.

There can only be one

We want to scope instances strictly per their container. So that foo is scoped in parent (thus visible from its child containers as well), and bar is scoped per childA. This appears to be the simplest setup, and the most in line with definition of singleton, but then we run into problems outlined above.

We then could add another constraint – dependencies can only face upwards the container hierarchy. We would then get foo with its dependency on bar pulled from parent container, consistently, regardless of the container we’d resolve it from. Moreover, we could resolve baz from childB and its dependency would be properly populated from parent since it comes from a container that is higher in the hierarchy, so we’re safe to pull that dependency.

On the other hand this robs us of one of nice (and often used) side effect of child containers, that is contextual overriding of components from containers higher up the hierarchy.

If we have bar in childA, we’d expect to get foo pulled via childA to have that bar, not parent’s bar.

Or perhaps not?

We can approach the problem from another angle altogether. We can narrow down the scope of a component instance, to the scope of its outermost dependency. What do I mean by that?

When resolving foo from childA the outermost dependency of foo would be the bar living in childA. Therefore the instance of foo would have bar pulled from parent, but scoped in childA. Therefore when we’d request foo again, but this time from childB we’d get another instance of foo, with dependency on bar pulled from parent. This could potentially lead to problems as well, since if you’re depending on the fact that single instance of your component will ever live in the application at given point in time you may end up with problems.

So what do you think? Which approach would you prefer, or is there something I’m missing here?

To those who though I’m seriously going to remove support for nested containers rest assured this is not going to happen. I still think this could be a viable option and I wanted to throw it into the air, but its become such a core feature of each IoC container, that Windsor would look crippled if it didn’t have it, regardless of whether or not it’d be actually needed.

Castle Windsor and child containers

Neal started looking into behaviour of child containers in Windsor. This is an area that’s very rarely used, and as Hammett wrote two years ago – this is speaking with the devil himself. No one really ever uses it so it never got well defined and as Neal found out there are certain inconsistencies, and grey areas there.

This was a don’t ask, don’t tell area, and since Neil opened that can of worms, it’s time to deal with the issue. I’m considering several solutions, and the one I’m leaning towards most would be probably the most controversial.

Remove support for child containers altogether?

Basically handler selectors and sub-resolvers give you all the power you need to handle scenarios where you would want to use child container instead. I think removing the child containers, and add some nicer support for contextual scoping of components would be the best solution.

The point of this post however is to get your thoughts on this issue. Are you using child containers in Windsor? What are you using it for? How are you using it? Write a comment or if you don’t want to share that in public just drop me an email. I’d really like to get a clean picture of how usage of this feature looks like at this point in time, before I make a decision.

.NET OSS dependency hell

Paul, whom some of you may know as the maintainer of Horn project, left a comment on my blog, that was (or to be more precise – I think it was) a continuation of series of his tweets about his dissatisfaction with the state of affairs when it comes to dependencies between various OSS projects in .NET space, and within Castle Project in particular.

paul_twitter

I must say I understand Paul, and he’s got some valid points there, so let’s see what can be done about it.

Problems

One of the goals of Castle Project from the very beginning has been modularity of its elements. As castle main page says:

Offering a set of tools (working together or independently) and integration with others open source projects, Castle helps you get more done with less code and in less time.

How do you achieve modularity. Say you have two projects, Foo and Bar that you want to integrate. You could just reference one from the other.

eb1c2cc[1]

This however means that whenever you use Foo, you have to drag Bar with you. For example, whenever you want to use MonoRail, you’d need to drag ActiveRecord with it, along with entire set of its dependencies, and their dependencies, etc.

Instead you employ Dependency Inversion (do not confuse with Dependency Injection). You make your components depend on abstractions, not the implementation. This however means, that in .NET assembly model, you need to introduce third assembly to keep the abstractions in.

51067fb6[1]

Now we have 3 assemblies instead of 2 to integrate two projects. Within Castle itself common abstractions are being kept in Castle.Core.dll. But what if we want to take more direct advantage of one project in another project still maintaining the decoupled structure? We need to extract the functionality bridging the two projects to yet another assembly. Tick – now we have 4 of them.

607f68d4[1]

In this case the FooBar project would be something like ActiveRecord integration facility, which integrates ActiveRecord with Windsor.

When you mix multiple projects together you enter another problem – versioning.

Say you want to integrate few projects together, some of which are interdependent (via bridging assemblies, not shown here for brevity)

69f20a13[1]

Now, once a new version of one of the projects is released, you either have to wait for all the other projects to update their dependency to the latest version, do it yourself (possibly with some help from Horn), or stick to the old version. The situation gets even more complicated when there were some breaking changes introduced, in which case plain recompilation will not do – some actual code would need to be written to compensate for that.

These are the main issues with this model, let’s now look at possible solutions.

Solutions

First thing that comes to mind – if having some assemblies means you’ll need even more assemblies, perhaps you should try to minimize that number? This has already come to our minds. With last wave of releases we performed some integration of projects. EmailSender got integrated into Core, one less assembly. Logging adapters for log4net and nlog were merged into core project, which means they still are separate assemblies (as they bridge Castle with 3rd party projects) but they’re now synced with Core and are released with it, which means this is one less element in your versioning matrix for you to worry about. Similar thing happened with Logging Facility, which now is versioned and released with Windsor itself.

For the next major version, there are suggestions to take this one step further. Merge DynamicProxy with DictionaryAdapter and (parts of) Core into a single assembly; Merge Windsor and MicroKernel (and other parts of Core) into an other assembly. With that you get from 5 assemblies to 2.

That reduces Castle’s internal dependencies, but what about other projects that depend on it? After the recent release, we started a log of breaking changes, along with brief explanation and suggested upgrade paths, to make it easier for applications and frameworks to upgrade. We have yet to see how this plays out.

What else can be done?

This is the actual question to you? What do you think can be done, for Castle specifically, but more broadly – for entire .NET OSS ecosystems to make problems Paul mentioned go away, or at least make them easier to sort out?

Learning in the Open: II – first relation and more ActiveRecord

It took a little longer than I planned but here we go again. In the meantime ActiveRecord 2.1 was released, and soon after that a minor update bringing one cool big feature. From now on we’ll be working on version 2.1.2. Picking up from where we left off last time. We have a user entity. Since we’re building a website where users can publish benchmark results, we’ll create now a benchmark entity, and create a relation between these two.

I want to see results!

Let’s start by adding an appropriate field to the User class:

private readonly ICollection<BenchmarkResult> benchmarkResults = new HashSet<BenchmarkResult>();

We also create a property:

public IEnumerable<BenchmarkResult> BenchmarkResults

{

    get

    {

        foreach (var result in benchmarkResults)

        {

            yield return result;

        }

    }

}

So far this is just a regular property. To map it as a one-to-many relation we use the HasManyAttribute.

[HasMany(Access = PropertyAccess.FieldCamelcase, 

    Cascade = ManyRelationCascadeEnum.SaveUpdate, 

    RelationType = RelationType.Set,

    Inverse = true)]

public IEnumerable<BenchmarkResult> BenchmarkResults

There’s quite a lot going on here, so let’s go over it piece by piece

  • Access property FieldCamelcase specify we want ActiveRecord (and NHibernate underneath it) to go to the field directly, which makes sense since we’re exposing it as mere enumerable.
  • Cascade specifies that when saving or updating our user, all new and changed benchmark results in the collection should also be appropriately saved or updated.
  • Usually we wouldn’t have to specify type of the relation. Usually it will infer it from the kind of collection we expose, and would use set for ISet, map for IDictionary, bag for ICollection etc. However since we’re exposing only IEnumerable it does not have enough information to decide, that’s why we have to be explicit here.
  • We also specify Inverse property to be true, which basically means that it’s child’s task to maintain the relationship. That also means that child needs to have a reference to the parent.

Let’s now build our BenchmarkResult class.

[ActiveRecord]

public class BenchmarkResult : ActiveRecordLinqBase<BenchmarkResult>

{

    protected BenchmarkResult()

    {

    }

 

    public BenchmarkResult(User user, string benmchmarkName, string computerModel, double score)

    {

        if (user == null)

        {

            throw new ArgumentNullException("user");

        }

        if (benmchmarkName == null)

        {

            throw new ArgumentNullException("benmchmarkName");

        }

        if (computerModel == null)

        {

            throw new ArgumentNullException("computerModel");

        }

 

        User = user;

        BenmchmarkName = benmchmarkName;

        ComputerModel = computerModel;

        Score = score;

    }

}

So far there’s nothing new here. Computer configuration and benchmark will become entities themselves soon, but let’s not get ahead of ourselves.

The only interesting property at this point is the User.

[BelongsTo]

public User User { get; private set; }

It has a BelongsToAttribute to denote it points to another entity (on our case the ‘one’ end of our one-to-many).

Let’s now let our users to actually save benchmark results, and we’re more or less done:

public BenchmarkResult RunBenchmark(string benchmarkName, string computerModel, double score)

{

    var result = new BenchmarkResult(this, benchmarkName, computerModel, score);

    benchmarkResults.Add(result);

    return result;

}

Test

We now have all the logic in place, so let’s build a test:

[Fact]

public void Can_perform_benchmark_runs()

{

    var stefan = new User

    {

        Email = "stefan@gmail.com",

        Name = "Stefan",

        Password = "Super compilcated password!",

        About = "Stefan is a very cool."

    };

    stefan.RunBenchmark("Foo bar!", "AyeMack Pro", 3.2);

    stefan.Save();

 

    var user = User.FindAll().Single();

 

    Assert.NotEmpty(user.BenchmarkResults);

    Assert.Equal(1, user.BenchmarkResults.Count());

 

    var result = user.BenchmarkResults.Single();

 

    Assert.NotNull(result);

    Assert.Equal("Foo bar!", result.BenmchmarkName);

    Assert.Equal("AyeMack Pro", result.ComputerModel);

    Assert.Equal(3.2, result.Score);

}

If we run it now, it will fail. Good news is, that it does not have anything to do directly with our logic. Bad news is, that we have a passing test nonetheless, so let’s have a look at it.

Error

We get “Incorrect syntax near the keyword ‘User’.” error message. Here’s the SQL that was sent to the database:

error_sql

Looks good doesn’t it? Well not – really, User is a SQL Server keyword, as we can’t just use it as identifier – we have to escape it. To do it, we have to specify the column name explicitly, and escape it by enclosing it within two ` characters (located above tab key on my keyboard).

Yes I’m aware of hbm2ddl.keywords auto-quote. However I had some issues getting it to work with ActiveRecord. Any help doing this will be appreciated.

[BelongsTo(Column = "`User`")]

public User User { get; private set; }

Now the test will pass, and the following SQL will be generated:

ok_sql

Now that we have the correct SQL, let’s look at what our schema looks like:

schema_inverse_true

Transparently releasing components in Windsor

Disclaimer:

This post is about the idea, not about the implementation. The implementation is crippled, not thread safe, will work only in few scenarios and only if used properly. Do not copy and blindly use this code.

The problem

One of unique features of Windsor is that it manages the lifecycle of objects it creates for you. What this means (among other things) is that it will dispose all disposable objects it instantiates. However to do this, it has to keep a reference to these components. Also that means that in order to properly release the components you have to get hold of the container and once you’re done using the components – explicitly release them with the container.

It may be not desirable from your perspective to do it like this. Ideally, you’d rather use your component, call Dispose and then have Windsor release the component. This is not quite possible, since there’s no way by which Windsor can be notified that your component was disposed. Or is there?

The idea

Since Dispose is an interface method and Windsor has quite powerful AOP capabilities, we can take advantage of that and intercept the call to Dispose and transparently release our component. Let’s build a disposable component first:

public interface IController : IDisposable

{

    int DoSomething();

 

    bool Disposed { get; set; }

}

 

public class Controller : IController

{

    // notice it's not virtual!

    public void Dispose()

    {

        // some clean up logic here

        Disposed = true;

    }

 

    public int DoSomething()

    {

        return 42;

    }

 

    public bool Disposed

    {

        get; set;

    }

}

One important thing to notice about this code – Dispose is not implemented virtually. This will make our sample simpler since we won’t have to deal with recursion.

Then we set up the stage:

[TestFixture]

public class TransparentReleasingTest

{

    private WindsorContainer container;

 

    [SetUp]

    public void SetUp()

    {

        container = new WindsorContainer();

        container.Register(Component.For<ReleaseComponentInterceptor>());

        container.Register(Component.For<IController>().ImplementedBy<Controller>()

                               .LifeStyle.Transient

                               .Interceptors<ReleaseComponentInterceptor>());

    }

 

    [TearDown]

    public void CleanUp()

    {

        container.Dispose();

    }

}

We’ll discuss the ReleaseComponentInterceptor, which is the gist of this post, in a minute. Let’s first create a test:

[Test]

public void Dispose_releases_component()

{

    IController item;

    using (var controller = container.Resolve<IController>())

    {

        item = controller;

        controller.DoSomething();

 

        Assert.IsTrue(container.Kernel.ReleasePolicy.HasTrack(controller));

        Assert.IsFalse(controller.Disposed);

    }

 

    Assert.IsFalse(container.Kernel.ReleasePolicy.HasTrack(item));

    Assert.IsTrue(item.Disposed);

}

Notice that in order for the interceptor to intercept the call to Dispose we need to cast component to IDisposable before calling the method (‘using’ will do that for us). Notice important aspect of this test – it is completely container agnostic. It does not need any kind of explicit nor indirect reference to the container to work and to release the component properly. Let’s now see what happens behind the scenes.

Interceptor

The hero of the day, is the following interceptor:

[Transient]

public class ReleaseComponentInterceptor : IInterceptor

{

    private static readonly MethodInfo dispose = typeof(IDisposable).GetMethods().Single();

    private readonly IKernel kernel;

 

    public ReleaseComponentInterceptor(IKernel kernel)

    {

        this.kernel = kernel;

    }

 

    public void Intercept(IInvocation invocation)

    {

        if (invocation.Method == dispose)

        {

            kernel.ReleaseComponent(invocation.Proxy);

        }

        else

        {

            invocation.Proceed();

        }

    }

}

Most of the time it just sits there and does nothing. However if it detects a call to Dispose, it releases the component from the container, which will in turn invoke the Dispose again (this time on the class, not interface, and since the interface is implemented non-virtually that second call won’t be intercepted), perform all other decommission job for the component as well as all its dependencies and it will release it, so that it can be garbage collected afterwards.

This is just another useful trick, worth knowing if you want to keep your design container agnostic while still reaping full benefits it provides.

Castle Windsor 2.1, Dynamic Proxy 2.2 and more released!

Update: Due to a regression error discovered in Windsor Factory Support Facility, we decided to act fast and provide updated package of Windsor, without the issue. Get it here. Sorry for the inconvenience.

Castle Project

What better way of starting a new year can there be, than fresh set of releases from Castle Project?!

Core 1.2 (with more)

Castle Core 1.2 has now its own, separate package. Since the beta few things have changed

  • Email sender component is now integrated with Core, so if you were using it, you now should look for it in Castle.Core.dll. The version shipped with Core 1.2 has the following major breaking changes:
    – Removed Message, MessageAttachment and MessageAttachmentCollection classes and replaced them with MailMessage, Attachment and AttachmentCollection from .NET classes in System.Net.Mail
  • Logging services (integration of Castle’s logging abstraction with log4net and NLog) is now packaged with Core. Notice that these are dependent on Core (just like it used to be). Castle does not have dependency on any of these, so don’t freak out.
  • few minor bugs were fixed, but nothing serious. You should be able to just switch the reference to new version and start using it with no changes to your code.
  • We ship four versions: for .NET 2.0, for .NET 3.5, for Silverlight 3.0 and for Mono 2.6

Get it here.

Dynamic Proxy 2.2

This is a pretty significant release. If you haven’t before, read what we had in beta. Since then, the following has changed

  • Interface members on proxies are behaving almost identical to version 2.1 (change from beta). That means that they take long name of explicit implementation (InterfaceName.Method() instead of Method()), only if you already have a method called Method() on your proxy, either from base class or other interface. And even then, it will still be public, which makes it more transparent to the user.
  • We ship three versions: for .NET 2.0 (this is the last version to support .NET 2.0), .NET 3.5 and Silverlight 3.0

Get it here.

MicroKernel/Windsor 2.1.1 (with support for Silverlight)

Probably the biggest thing about this release is that it includes a Silverlight version. There are a couple more highlights thought

  • revamped typed factory facility
  • added ability to specify Type Forwarding via XML config with the following syntax:
    <component

      id="hasForwards"

      type="Castle.MicroKernel.Tests.ClassComponents.TwoInterfacesImpl, Castle.MicroKernel.Tests"

      service="Castle.MicroKernel.Tests.ClassComponents.ICommon, Castle.MicroKernel.Tests">

      <forwardedTypes>

        <add service="Castle.MicroKernel.Tests.ClassComponents.ICommon2, Castle.MicroKernel.Tests" />

      </forwardedTypes>

    </component>

  • added DynamicParameters (with additional option to return delegate to be called upon component’s destruction)
  • added OnCreate method, which lets you act upon component after it’s created, and before it’s removed (see this Tehlike’s post. Notice it’s not in a facility now, so it just works out of the box.)
  • added lazy component loader
  • major performance improvements in certain scenarios
  • and many bugfixes, see commit log for full list if you’re interested
  • We ship two versions: for .NET 3.5 and for Silverlight 3.0
  • There is also logging facility included in the package. Again – neither MicroKernel, nor Windsor depend on it, so don’t freak out.

Get it here.

We’re already gathering ideas for the next version, so go ahead to the Castle UserVoice page and tell us, what you’d like to see in the next version!

Learning in the Open: I – Starting with ActiveRecord

We’re building an application to gather and compare performance metrics of various laptop configurations in given set of benchmarks. As such we’re going to start with certain set of entities, first of which will be the User. We’ll start off by defining our User entity, configuring ActiveRecord, and some basic tests.

Getting started

First thing’s first – we need to get ourselves a fresh version of required libraries. At this point in time I’m using the trunk version. You can get the latest binaries here. Everything I show here will work with ActiveRecord 2.1 final version though.

So let’s create ourselves a new solution, with class library and add required references:

references

We need Castle.ActiveRecord.dll, Castle.ActiveRecord.Linq.dll, which is where integration with NHibernate.Linq lives, and NHibernate.dll. Having that in place we can start coding our first entity.

User is always right

Let’s start by declaring our User class:

[ActiveRecord]

public class User : ActiveRecordLinqBase<User>

{

}

We mark our class with ActiveRecordAttribute. By doing this we let Active Record know that this class is persistent. We use ActiveRecordLinqBase<User> as our base class. This gives us access to all standard Active Record pattern methods, as well as IQueryable<User> so that we can use LINQ to query for our users. Alternatively if we didn’t want to have this base class we can use ActiveRecordMediator<User> which provides the same persistence services as our base class.

Now, that we told ActiveRecord it should persist our User class, we’ll need a primary key property.

private Guid id;

 

[PrimaryKey(Access = PropertyAccess.NosetterCamelcase)]

public Guid Id

{

    get { return id; }

}

Couple of things to notice about this piece of code. We use PrimaryKeyAttribute to mark our property as holding primary key. Also we use Guid as our surrogate primary key type, for several reasons. If you’ve used older versions of ActiveRecord, you may notice I didn’t specify primary key generator kind. ActiveRecord 2.1 will infer it from property type and will use guid.comb. We also don’t expose setter for this property. By using PropertyAcess.NosetterCamelcase we tell ActiveRecord to use getter to retrieve value of this property, and to use backing field which has identical name as the property, but written in camel case to write it.

We’re going to need a couple of other properties for our users:

[Property(Unique = true, NotNull = true)]

public string Name { get; set; }

 

[Property]

public string Email { get; set; }

We use PropertyAttribute to mark properties that should be persisted. While we don’t put any non default constraints on the Email property at this point, we’ll make user name unique, and we’ll disallow nulls.

[Property(Access = PropertyAccess.FieldCamelcase)]

public string Password { set { password = Hash(value); } }

 

[Property(Length = 10000)]

public string About { get; set; }

For password we expose only setter. Also since we don’t want to store passwords of our users, we hash it, and store the hash. About is a property that has Length set to 10000. This means nvarchar(max) for SQL Server 2005 (which is what we’ll use) or corresponding data type if you use other database engine.

Let’s set up a test project for ourselves and start writing some basic logic. But before we do this, we’ll need to set up a database and configure ActiveRecord.

Configuration

For our database we’ll use SQL Server .mdf file. When we create it, we’ need to create an AppDomain configuration file and put some basic configuration in it. We could alternatively put ActiveRecord configuration in some other file it we wanted.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

    <section name="activerecord"

             type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord" />

  </configSections>

    <connectionStrings>

        <add name="Wawel"

             connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=f:\ComputerBenchmark\sql\Wawel.mdf;Integrated Security=True;User Instance=True"

             providerName="System.Data.SqlClient" />

    </connectionStrings>

  <activerecord pluralizeTableNames="true">

    <config database="MsSqlServer2005"

            connectionStringName="Wawel" />

  </activerecord>

</configuration>

We start by declaring active record section and registering handler for it. We then put standard Active Record configuration. We tell it to pluralizeTableNames, so that for our User class a Users table will be created. We then specify what kind of database engine we want to use (MsSqlServer2005) and name of the connection string to use. That’s it. If you’ve used previous versions of ActiveRecord you may remember it used to require quite a bit more configuration. Now it will just use default values for these, which you can always override if you want. We can now move on to creating tests.

Tests

We’ll use XUnit.NET as our testing framework. Sine ActiveRecord is built on top of NHibernate we also use NHProf to gain insight into what’s going on under the cover. Here’s the setup code.

public class UserTests:IDisposable

{

    public UserTests()

    {

        // performs initialization using information from appdomain config file

        ActiveRecordStarter.Initialize();

        // registers all active record types from the assembly

        ActiveRecordStarter.RegisterAssemblies(typeof(User).Assembly);

        // generates database schema

        ActiveRecordStarter.UpdateSchema();

 

        NHibernateProfiler.Initialize();

    }

 

    public void Dispose()

    {

        NHibernateProfiler.Stop();

        ActiveRecordStarter.DropSchema();

 

        // this is only for tests

        ActiveRecordStarter.ResetInitializationFlag();

    }

}

ActiveRecordStarter.Initialize reads all settings from the app.config file we discussed above and initializes its engine. We then feed it with information about our Active Record classes, and call UpdateSchema. ActiveRecord will now generate our complete database schema for us.

sshot-2

As you can see table name is nicely pluralized, and all the information we specified in attributes was used to create correct schema. Having that, we can now create our first test.

[Fact]

public void Can_save_and_read_User()

{

    var stefan = new User

    {

        Email = "stefan@gmail.com",

        Name = "Stefan",

        Password = "Super compilcated password!",

        About = "Stefan is a very cool."

    };

 

    stefan.Save();

    var users = User.Queryable

        .Where(u => u.Name.StartsWith("S"))

        .ToList();

    Assert.NotEmpty(users);

    Assert.Equal("Stefan", users.Single().Name);

}

We create a user, than call method Save, inherited from our base class which persists the user to the database. We then can use static Queryable property which exposes LINQ engine to create a fancy LINQ query to retrieve our user.

sshot-3

Fantastic! We have a working persistent user entity!

Learning in the open – Sample application for Castle stack

We’re getting really close to new release of major Castle Project elements (Monorail 2.0, ActiveRecord 2.1, Windsor 2.1…). Coincidently I started building a small application on top of the stack, and I thought it would be a good idea to make this a “learning in the open” experience, and share my progress on this blog.

This will mostly (at least initially) be a rework of Ayende’s old series, but I will update it to the latest version of the projects and try to discuss some new features as we go along.

I don’t have the application ready yet. This is a journey for me, and as I don’t really have much experience with either Monorail or ActiveRecord, I may do stupid things. That’s the part where your feedback comes into play. I want to drive this series on feedback in much greater degree than the series on Dynamic Proxy. If you want me to dive into details on certain topics – let me know. If you think I should have done something differently and revisit some parts – let me know.

That’s all for now – see you next time.

Castle Typed Factory Facility reborn

Disclaimer:

Notice that code shown here is quite new and is subject to change. If you’re reading this and it’s 2010 it’s likely that the code now is slightly different. I may come back and revisit the post if there are any changes, but don’t hold my word on it.

Pulling from the container

General rule of thumb when using IoC containers is – when you’re referencing your container in your components (anywhere outside of your bootstrapping code) you’re doing it wrong. As with all rules there are exceptions, but they are rare. Still, there are cases where you have to pull from the container somehow. What to do then? Let’s use the following artificial example:

public class MessageDispatcher

{

    public void Dispatch(IMessage message)

    {

        var handler = GetHandlerFor(message);

        handler.Handle(message);

        Destroy(handler);

    }

 

    private IMessageHandler GetHandlerFor(IMessage message)

    {

        // how to implement this...

    }

 

    private void Destroy(IMessageHandler handler)

    {

        // ... and this?

    }

}

Solution – take one – the ugly

The easiest option to implement is just to take dependency on the container.

private IKernel container;

private IMessageHandler GetHandlerFor(IMessage message)

{

    return container.Resolve<IMessageHandler>(new { name = message.Name });

}

 

private void Destroy(IMessageHandler handler)

{

    container.ReleaseComponent(handler);

}

This option seems the easiest at first. You just call the container directly. However along the way you coupled your component to the container which has whole list of disadvantages and is the wrong thing to do.

Solution – take two – the bad

Ok, so if calling the container directly is bad, we can use a layer of abstraction on top of it, right? Like Common Service Locator for example… This way we can swap the container underneath which proves the component has no dependency on the container.

Well, this is certainly a step in the right direction, but it still has a whole range of flaws. First of all – it won’t work in our scenario. Take a closer look at the code above – when we’re resolving the message handler, we’re also passing an argument in. CSL does not support passing parameters. Besides, using CSL just hides the problem instead of solving it – you’re still having a dependency on an infrastructure library in your domain component.

Solution – take three – the good

The least worst way of solving this problem is to introduce dedicated factory which will hide the container from your domain. Doing this manually (provided you want to do it right) is however a lot of tedious boring work. You have to define an interface for your factory in your domain assembly, then create an implementation in another one, then actually implement all the calls (and not only to resolve, don’t forget about cleaning up after yourself), which as you’ll soon discover is a lot of repetitious code.

public class MessageDispatcher

{

    public void Dispatch(IMessage message)

    {

        var handler = GetHandlerFor(message);

        handler.Handle(message);

        Destroy(handler);

    }

 

    private void Destroy(IMessageHandler handler)

    {

        factory.DestroyHandler(handler);

    }

 

    private IMessageHandlerFactory factory;

 

    private IMessageHandler GetHandlerFor(IMessage message)

    {

        return factory.CreateNewHandler(message.Name);

    }

}

 

public interface IMessageHandlerFactory

{

    IMessageHandler CreateNewHandler(string name);

 

    void DestroyHandler(IMessageHandler handler);

}

 

// in another assembly

public class MessageHandlerFactory : IMessageHandlerFactory

{

    private IKernel container;

    public IMessageHandler CreateNewHandler(string name)

    {

        return container.Resolve<IMessageHandler>(new { name =name });

    }

 

    public void DestroyHandler(IMessageHandler handler)

    {

        container.ReleaseComponent(handler);

    }

}

Wouldn’t it be good if someone else could do the work for you? – Meet Typed Factory Facility.

Windsor Typed Factory Facility

Typed factory is just the tool for this problem – it’s an automatically created factory, created by container, but your code is unaware of the container. It’s been around since 2005 but due to severe limitations imposed on it, and lack of development in recent years it hasn’t been widely used.

However it’s been recently retuned, with new capabilities and old limitations have been removed. It’s considerably more usable now, hence the word reborn in the title on this post. Let’s get to the code, shall we?

var container = new WindsorContainer();

container.AddFacility<TypedFactoryFacility>();

container.Register(

    // register the handler and all the other components

    Component.For<MessageDispatcher>(), // register the component with dependency on our factory

    Component.For<IMessageHandlerFactory>().AsFactory() //register the factory itself (just the interface)!

    ); // that's it, now get the dispatcher

var dispatcher = container.Resolve<MessageDispatcher>();

//start dispatching...

we register the facility with the container, than we register all the components the usual way. When we want to use an interface as a factory, we register it without any implementation (if you pass an implementation it will be ignored) and then call the AsFactory() extension method, and we’re all set.

Now the kernel will implement the factory for you based on few conventions

  • all the void methods are assumed to be used to release components passed as arguments
  • all the non-void methods are assumed to be used to resolve components from the container
  • If the factory implements IDisposable, the call to dispose will release all the transient components that were resolved via the factory.

Now, how does the factory know which service to request from the container? By default:

  • Method’s return type is used to request the component by type
  • If the method on the factory interface is called GetSOMETHING, the component called SOMETHING will be requested by name
  • All the arguments passed to the method, will be forwarded to the container with names of the method’s parameters.

This however, is just the default behavior – you can easily change it, by implementing ITypedFactoryComponentSelector and registering it with the container. Then your implementation will be picked, and used to bind factory methods and their arguments to information used by the resolve appropriate components.

Custom ITypedFactoryComponentSelector – example

For example, let’s say you don’t like the GetSOMETHING convention, and decided that if the first argument of typed factory method is a string, it should be bound to component’s name instead.

public class MySelector: ITypedFactoryComponentSelector

{

    public TypedFactoryComponent SelectComponent(MethodInfo method, Type type, object[] arguments)

    {

        string componentName = null;

        if(arguments.Length>0 && arguments[0] is string)

        {

            componentName = arguments[0].ToString();

        }

 

        //let's ignore all other arguments here for simplicity sake

        return new TypedFactoryComponent(componentName, method.ReturnType, null);

    }

}

Little bonus

One thing about this facility that blew my mind, is that the factory is not limited to resolving a single type –  with literally no effort you can use it to build a generic service locator.

public interface IGenericFactory

{

    T Create<T>();

}

 

var factory = container.Resolve<IGenericFactory>();

 

var one = factory.Create<ISomeComponent>();

var two = factory.Create<IOtherComponent>();

The code is in the trunk. It may still contain bugs and not support all scenarios, so approach with caution, and as always – any feedback is appreciated.

Technorati Tags:

Overriding generic component’s resolution in Castle Windsor

Few months ago, a user asked the following question on the Castle users discussion group. A friend asked me about the same thing today, so I thought I’d blog this so that’s easier to find than the discussion group thread. Anyway, here’s the question:

say I have the following types

public interface ISometype<T> {} 

public class SomeTypeImpl<T>:ISometype<T> {} 

public class SomeSpecificTypeImpl<T>:ISometype<T> where T: ISomeSpecificSpecifier {} 

public interface ISomeSpecificSpecifier { } 

Is there a way to register ISomeType<> in the container so that for the general case it uses SomeTypeImpl<> but for cases where T is ISomeSpecificSpecifier it could use SomeSpecificTypeImpl<>?

Solution take one – the explicit version

The solution may be similar to the following sketchy code.

class Program

{

    static void Main(string[] args)

    {

        var container = new WindsorContainer();

        container.Register(Component.For(typeof(ISometype<>)).ImplementedBy(typeof(SomeTypeImpl<>)),

                           Component.For(typeof(ISometype<>)).ImplementedBy(typeof(SomeSpecificTypeImpl<>))

                               .PreferredFor<ISomeSpecificSpecifier>());

        var selector = new Selector();

        container.Kernel.AddHandlerSelector(selector);

 

        var sometype = container.Resolve<ISometype<string>>();

        Debug.Assert(sometype.GetType() == typeof(SomeTypeImpl<string>));

 

        var sometype2 = container.Resolve<ISometype<Specifier>>();

        Debug.Assert(sometype2.GetType() == typeof(SomeSpecificTypeImpl<Specifier>));

    }

}

 

public static class Preferred

{

    public static ComponentRegistration<object> PreferredFor<TClosingGenericType>(this ComponentRegistration<object> registration)

    {

        return registration.ExtendedProperties(new Preference(typeof(TClosingGenericType)));

    }

}

 

internal class Preference

{

    public static readonly string Name = "PreferredForClosingType";

    public Type PreferredForClosingType { get; set; }

 

    public Preference(Type type)

    {

        this.PreferredForClosingType = type;

    }

}

 

public class Selector : IHandlerSelector

{

    public bool HasOpinionAbout(string key, Type service)

    {

        // that's about as much as we can say at this point...

        return service.IsGenericType && service.GetGenericArguments().Length == 1;

    }

 

    public IHandler SelectHandler(string key, Type service, IHandler[] handlers)

    {

        var @default = handlers.FirstOrDefault(h => MatchHandler(service, h));

        return @default ?? handlers.First();

    }

 

    private bool MatchHandler(Type service, IHandler handler)

    {

        if (handler.ComponentModel.ExtendedProperties.Contains(Preference.Name) == false)

            return false;

        var closingTypeRequired = (Type)handler.ComponentModel.ExtendedProperties[Preference.Name];

        var closingTypeActual = service.GetGenericArguments().Single();

        return closingTypeRequired.IsAssignableFrom(closingTypeActual);

    }

}

This version contains an explicit extension to the component registration API, to specify which component you prefer in which case. It also uses and IHandlerSelector implementation to do the actual work during resolution. It is possible however to not extend the API, and use the information we already have

Solution take two – the implicit version

class Program

{

    static void Main(string[] args)

    {

        var container = new WindsorContainer();

        container.Register(Component.For(typeof(ISometype<>)).ImplementedBy(typeof(SomeTypeImpl<>)),

                           Component.For(typeof(ISometype<>)).ImplementedBy(typeof(SomeSpecificTypeImpl<>)));

        var selector = new Selector();

        container.Kernel.AddHandlerSelector(selector);

 

        var sometype = container.Resolve<ISometype<string>>();

        Debug.Assert(sometype.GetType() == typeof(SomeTypeImpl<string>));

 

        var sometype2 = container.Resolve<ISometype<Specifier>>();

        Debug.Assert(sometype2.GetType() == typeof(SomeSpecificTypeImpl<Specifier>));

    }

}

 

public class Selector : IHandlerSelector

{

    public bool HasOpinionAbout(string key, Type service)

    {

        // that's about as much as we can say at this point...

        return service.IsGenericType && service.GetGenericArguments().Length == 1;

    }

 

    public IHandler SelectHandler(string key, Type service, IHandler[] handlers)

    {

        return handlers.FirstOrDefault(h => MatchHandler(service, h));

 

    }

 

    private bool MatchHandler(Type service, IHandler handler)

    {

        var closingTypeRequired = handler.ComponentModel.Implementation.GetGenericArguments()

            .Single().GetGenericParameterConstraints().SingleOrDefault();

        if (closingTypeRequired == null)

            return false;

        var closingTypeActual = service.GetGenericArguments().Single();

        return closingTypeRequired.IsAssignableFrom(closingTypeActual);

    }

}

This version relies on the information provided in component’s generic type constraints. The Registration API is not extended, and we just do a little bit more work in the selector. Is this version better? It depends. The explicit version is… well – explicit about what it does, and for which components. The implicit one works on its own and if you’re not careful you may end up chasing very strange bugs in your code. That said, if you do go for the second option, be sure to at least add some diagnostics logging to it, so that you can see what it does when you’re not watching.

Technorati Tags: