This post is a playground for me, to try out some ideas I want to include in my talk about Windsor at KGD.NET meeting later this month.
Scenario
We have a messaging application built around two interfaces:
public interface Command
{
}
public interface Handler
{
void Execute();
}
public interface Handler<T> : Handler where T : Command
{
T Command { get; set; }
}
Hopefully I don’t have to explain how they work. The idea is, application receives commands from somewhere, then it pulls all handlers registered for this command and let them handle the command. Split of Handler interface into generic and non-generic part is there to make up for lack of co/contra-variance in .NET 3.5.
Commands and Handlers
Handlers are quite simple classes implementing closed version of Handler<> interface. For example to change client’s address we’d have the following command
[Serializable]
public class UpdateClientCorrespondenceAddressCommand : Command
{
private readonly AddressDto address;
private readonly Guid clientId;
public UpdateClientCorrespondenceAddressCommand(Guid clientId, AddressDto address)
{
this.clientId = clientId;
this.address = address;
}
public AddressDto Address
{
get { return address; }
}
public Guid ClientId
{
get { return clientId; }
}
}
and its handler:
public class UpdateClientCorrespondenceAddressHandler : Handler<UpdateClientCorrespondenceAddressCommand>
{
private readonly Repository<Client> clientRepository;
public UpdateClientCorrespondenceAddressHandler(Repository<Client> clientRepository)
{
this.clientRepository = clientRepository;
}
public UpdateClientCorrespondenceAddressCommand Command { get; set; }
public void Execute()
{
var command = Command;
if (command == null) return;
var client = clientRepository.Get(command.ClientId);
client.ChangeCorrespondenceAddress(command.Address);
clientRepository.Update(client);
}
}
Nothing earth shattering here. We would have similar set up for other business events in the application. We assume we can have more than one handler for single command (for example another handler would update shipping costs and promotions available for the new address of the client).
The ability to pull multiple services from the container via typed factory is not available in Windsor 2.1.1 – you need the trunk version to take advantage of it.
Registration
To register the code we create an installer:
public class Installer : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>()
.Register(
Component.For<ITypedFactoryComponentSelector>().ImplementedBy<HandlerSelector>(),
Component.For<AutoReleaseHandlerInterceptor>(),
AllTypes.FromAssemblyContaining<Program>()
.BasedOn(typeof(Repository<>))
.WithService.Base()
.Configure(c => c.LifeStyle.Singleton)
.BasedOn(typeof(Handler<>))
.WithService.Base()
.Configure(c => c.LifeStyle.Is(LifestyleType.Transient)
.Interceptors<AutoReleaseHandlerInterceptor>()),
Component.For<HandlerFactory>().AsFactory());
}
}
There are a couple interesting things here. First we register typed factory facility, which we’ll use later on to pull handlers for commands we receive. Then we register custom selector for typed factory (discussed below), and an interceptor (discussed below). Then we register all repositories and all handlers from given assembly, configuring handlers with transient lifestyle and with the interceptor we registered above. Lastly we also register typed factory for handlers:
public interface HandlerFactory
{
Handler[] GetHandlersForCommand(Command command);
}
Typed factory selector
The handler factory has to do quite a lot of work for us. Given an instance of a command, it has to pull from the container all the handlers for the command’s type. To do this we need to use a custom selector (and trunk version of Windsor).
public class HandlerSelector:ITypedFactoryComponentSelector
{
public TypedFactoryComponent SelectComponent(MethodInfo method, Type type, object[] arguments)
{
Debug.Assert(arguments.Length == 1);
var message = arguments[0];
var handlerType = typeof(Handler<>).MakeGenericType(message.GetType());
return new TypedFactoryComponentCollection(handlerType.MakeArrayType(), new Arguments(arguments));
}
}
Based on the command’s type we create closed Handler<> type and return TypedFactoryComponentCollection (new type that pulls all components for given service) passing down the command as typed argument to the resolution.
Putting it all together
We can now use the code like this:
private static void Main()
{
using(var container = new WindsorContainer().Install(new Installer()))
{
var factory = container.Resolve<HandlerFactory>();
DoActualWork(factory);
Console.ReadKey(true);
}
}
private static void DoActualWork(HandlerFactory factory)
{
var command = ImmitateCommandArrived();
var handlers = factory.GetHandlersForCommand(command);
foreach (var handler in handlers)
{
handler.Execute();
}
}
private static Command ImmitateCommandArrived()
{
return new UpdateClientCorrespondenceAddressCommand(Guid.NewGuid(), GetSomeAddress());
}
Notice how simple the calling code is. It has no knowledge of the (quite complex) process that takes place behind the scenes to create strongly typed instances of appropriate classes. It does not even know what actual type of command it got.
What about releasing transient handlers?
Isn’t this code too simple though? It resolves handlers, which are transient components and it does not release them. And we all know transient components need to be released in Windsor, right?
Well – it does release them actually, it just doesn’t do it explicitly. Remember we registered an interceptor with all handlers. Here’s how that interceptor looks like:
[Transient]
public class AutoReleaseHandlerInterceptor : IInterceptor
{
private static readonly MethodInfo Execute = typeof(Handler).GetMethod("Execute");
private readonly IKernel kernel;
public AutoReleaseHandlerInterceptor(IKernel kernel)
{
this.kernel = kernel;
}
public void Intercept(IInvocation invocation)
{
if(invocation.Method!=Execute)
{
invocation.Proceed();
return;
}
try
{
invocation.Proceed();
}
finally
{
kernel.ReleaseComponent(invocation.Proxy);
}
}
}
The interceptor releases the component after the call to Execute for us. Thanks to this we take the burden (no pun intended) of releasing the components from the callers, and we make sure our handlers won’t leak memory. This is quite a useful trick actually, and while I have precisely zero knowledge of NServiceBus, I think it could be used to fix the issue Davy discussed, without having to mess with release policy.
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.
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.
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.
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.
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)
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?
With Windsor 2.1.1 out the door, we’re already working on version 3.0 (and looking for your feedback and ideas for the next version!). Yesterday I committed first “big” feature that probably will make it to the release.
DISCLAIMER:
All the code shown here represents a work in progress. Keep in mind that final version may be different. This also means that any feedback on this feature is appreciated.
Named Arguments
In current version of Windsor you can define inline dependencies for a component in at least three different ways:
- When registering it (with value obtained at registration time):
container.Register(
Component.For<ICustomer>()
.ImplementedBy<CustomerImpl>()
.DependsOn(
Property.ForKey("Name").Eq("Caption Hook"),
Property.ForKey("Address").Eq("Fairyland"),
Property.ForKey("Age").Eq(45)
)
);
- When registering it (with value obtained at resolution time), AKA – Dynamic Parameters
container.Register(
Component.For<ClassWithArguments>()
.LifeStyle.Transient
.DynamicParameters((k, d) =>
{
d["timeStamp"] = DateTime.Now;
d["user"] = Thread.CurrentPrincipal.Identity;
})
);
- When resolving it (although this is something you should strive to avoid, using constructor injection and/or Typed factory facility)
var component = container.Resolve<ClassWithArguments>(new
{
TimeStamp = DateTime.Now,
User = Thread.CurrentPrincipal.Identity
});
What all these approaches have in common is that you specify dependency by name. Windsor when resolving the component will then use the value you provided for constructor arguments or settable properties with that name it finds on the component. What if you don’t care about the name?
Typed Arguments
Trunk version of Windsor lets you do just that – omit the name in which case Windsor will use the type of the argument as the sole information when building your component.
container.Register(
Component.For<ClassWithArguments>()
.Lifestyle.Transient
.DependsOn(
Property.ForKey<DateTime>().Eq(DateTime.Now),
Property.ForKey<IIdentity>().Eq(Thread.CurrentPrincipal.Identity))
);
As you can see here we use the type as the key for the dependency. This works also with dynamic parameters as well as when passing arguments straight from the call site. A new class – Arguments has been introduced to accommodate this new feature (although ordinal Hashtable or Dictionary<object,object> will do just fine as well) .
container.Resolve<ClassWithArguments>(
new Arguments(new object[]
{
DateTime.Now,
Thread.CurrentPrincipal.Identity
})
);
The Arguments class itself implements IDictionary and can wrap either another IDictionary containing either named or typed arguments, anonymous type containing named arguments or array of objects to be used as typed arguments. It is advised to use this type when you plan to use typed arguments.
Additionally to help you deal with filling the dictionaries in more usable fashion an extension method on IDictionary (so they work for Arguments type as well) called Insert (with few overloads) has been introduced. It lets you insert arguments in a fluent, more user friendly fashion.
container.Register(
Component.For<ClassWithArguments>()
.DynamicParameters((k, d) =>
d.Insert(DateTime.Now)
.Insert(Thread.CurrentPrincipal.Identity))
);
Final words
While this may be appealing at first to use typed arguments everywhere, resist the temptation unless you have a good reason. Named arguments should always be your first choice. Name is a valuable contextual information that may improve the readability of your code. Windsor will favor named arguments over typed and use the latter only if it can’t find a matching named argument.
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:
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:
Now that we have the correct SQL, let’s look at what our schema looks like:

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.
I’m sure many of you, even those who use ReSharper on a daily basis, almost never use one of its most powerful features – live templates.
I just love how with single shortcut (ctrl + alt + insert) I can go to
enter, I go to
Type class name, enter
and I have just saved roughly 30s as compared to bare Visual Studio, but most importantly, I didn’t loose my momentum and focus. Sure it’s a small thing, but that’s how you build a palace – brick by brick.
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.

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!
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:
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.
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.
Fantastic! We have a working persistent user entity!
Jimmy published very interesting post about generic registration of certain partially closed types in StructureMap container. Go read the entire post first, it’s really worth it.
You’re back? OK. Jimmy uses StructureMap container in his sample, and after I saw it I immediately thought about doing the same thing in Windsor. That’s what this post is all about – how to make the following test pass:
Test
[Test]
public void Should_connect_delete_handler()
{
var container = new WindsorContainer();
container.AddFacility<HandlerFacility>();
container.Register(AllTypes.FromAssemblyContaining<DeleteCustomerCommand>()
.BasedOn<IEntity>()
.BasedOn(typeof(IHandler<>)).WithService.Base()); // [a]
var handler = container.Resolve<IHandler<DeleteEntityCommand<Customer>>>();
Assert.IsInstanceOf<DeleteEntityCommandHandler<Customer>>(handler);
}
Solution
The line marked with [a] registers types implementing IHandler<>. It will register DeleteEntityCommandHandler<> with IHandler<>. This is the equivalent of StructureMap’s ConnectImplementationToTypesClosing in Windsor.
As you can see I also registered a facility – HandlerFacility which does the actual magic, and is unsurprisingly quite similar to Jimmy’s DeleteCommandRegistrationConvention.
public class HandlerFacility : AbstractFacility
{
private static readonly Type openDeleteCommandType = typeof(DeleteEntityCommand<>);
private static readonly Type openHandlerInterfaceType = typeof(IHandler<>);
private static readonly Type openDeleteCommandHandlerType = typeof(DeleteEntityCommandHandler<>);
protected override void Init()
{
Kernel.HandlerRegistered += OnHandlerRegistered;
}
private void OnHandlerRegistered(IHandler handler, ref bool statechanged)
{
var type = handler.ComponentModel.Implementation;
if (type.IsAbstract || typeof(IEntity).IsAssignableFrom(type) == false)
{
return;
}
var closedDeleteCommandType = openDeleteCommandType.MakeGenericType(type);
var closedHandlerInterfaceType = openHandlerInterfaceType.MakeGenericType(closedDeleteCommandType);
var closedDeleteCommandHandlerType = openDeleteCommandHandlerType.MakeGenericType(type);
Kernel.Register(
Component.For(closedHandlerInterfaceType)
.ImplementedBy(closedDeleteCommandHandlerType)
.LifeStyle.Transient);
}
}
Just to set the record straight - you don’t really need a facility for that .You could hook an anonymous delegate to container kernel’s event and do that work inline. Having a facility is however my preferred solution since it encapsulates the work nicely, and gives you access to configuration, provided you’d ever want to externalize some part of the facility.
That’s all we needed to make the test pass:

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.