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.
As some of you know, I’m not a web developer. I had a short affair with webforms, which ended… quickly leaving bad taste in my mouth. However it’s hard to ignore positive buzz around Microsoft’s “other” framework for building web applications – namely ASP.NET MVC. Especially it’s hard to ignore that the buzz comes from people I know, respect and hope they know what they’re talking about. I was quite happy to see that some of these people wrote a book about this framework so I decided to pick it up. I was expecting a great book, and a great book I got.
ASP.NET MVC in Action, judging from the title has a clear purpose – bringing you up to speed with the said framework. Most ‘framework’ (or language) books take an easy approach to the task – you get basically annotated specification with few better or worse samples and you’re left with figuring out (based on your own mistakes most of the time), which elements to use, and which not, how to use the framework/language in broader context of application and how to leverage its strengths to build testable, maintainable application that you ship and hopefully make money on. So is this book like that – no, and that’s its single greatest feature.
While the book does a good job at teaching you how to use the framework, it’s as much about the framework as about principles. I didn’t count but in the first chapter alone, I think word ‘testable’ appears more time than the word ‘MVC’. You get to learn about maintainability as much as about view helpers, onion architecture, as much as about controller actions… I think you get the idea.
But wait – there’s more. ASP.NET MVC is not a lonely island, it enters an existing (and growing) ecosystem of other tools and frameworks. The authors acknowledge that fact, and take full advantage of it. As as result of that you’ll learn as much about the framework’s API, as about how to plug it with extending projects (MVCContrib) how to use it in conjunction with IoC containers, persistence frameworks etc. All that while still keeping an eye on maintainability and proven practices. And to help you choose wisely, it contains an entire chapters dedicated to direct competitors of ASP.NET MVC – Castle Monorail, and Ruby on Rails.
While no book can make you a better developer by itself, they can be a great help in pointing you into right directions, guiding you to avoid pitfalls and common mistakes, and this by all means is such a book.
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:
Castle Windsor
UPDATE:
I renamed the method from WithParameters to DynamicParameters to avoid confusion and be consistent with Parameters method which is used for static parameters.
I just committed small new feature to Castle Windsor, that I think can nicely clean up your code. It remedies the following problem:
Problem
What if you have a component that relies on a dynamically provided primitive value? Things like current request’s Uri, or DateTime.Now?
public class UsesCurrentTime
{
UsesCurrentTime(DateTime currentTime)
{
Console.WriteLine("Current time is {0}”, currentTime);
}
}
Solution – the old way
Until now you had two choices:
- wrap the dependency in a service, like ICurrentUriProvider, or IClock and take dependency on that interface
public class UsesCurrentTime
{
UsesCurrentTime(IClock currentTime)
{
Console.WriteLine("Current time is {0}", currentTime.Now);
}
}
- in the code using that service, reference the container and pull the service yourself, instead of having it injected.
public class Uses_UsesCurrentTime
{
private IKernel container;
public void DoSomethingWithCurrentTime()
{
var service = container.Resolve<UsesCurrentTime>(new {currentTime = DateTime.Now});
// do something with the service here
}
}
Neither of these approaches is ideal. The new feature I mentioned is here to save the day. It basically lets you take the best of both approaches, without paying their price. You get to pass the parameters without additional layer of indirection, and without referencing container and pulling the service manually.
Solution – the new way
To use it, we need to use a new method on the fluent registration API: DynamicParameters, like this.
kernel.Register(
Component.For<UsesCurrentTime>()
.LifeStyle.Transient
.DynamicParameters((kernel, parameters) => parameters["currentTime"] = DateTime.Now));
the method takes a delegate that will be invoked when the component is being resolved, but before any actual resolution, parameter matching, appropriate constructor searching etc happens. It gives you access to two things: the container itself, and the dictionary of parameters, that were passed from the call site. You can then inspect the parameters, add new, remove them, etc.
What’s more interesting – you can use it not only for primitives. You can also dynamically override components.
kernel.Register(
Component.For<ICustomer>()
.ImplementedBy<CustomerImpl>()
.Named("defaultCustomer"),
Component.For<ICustomer>().ImplementedBy<CustomerImpl2>()
.Named("otherCustomer")
.Parameters(
Parameter.ForKey("name").Eq("foo"), // static parameters, resolved at registration time
Parameter.ForKey("address").Eq("bar st 13"),
Parameter.ForKey("age").Eq("5")),
Component.For<CommonImplWithDependancy>()
.LifeStyle.Transient
.DynamicParameters((k, d) => // dynamic parameters
{
var randomNumber = 2;
if (randomNumber == 2)
{
d["customer"] = k.Resolve<ICustomer>("otherCustomer");
}
}));
var component = kernel.Resolve<CommonImplWithDependancy>();
Assert.IsInstanceOf<CustomerImpl2>(component.Customer);
This test will pass.
Technorati Tags:
Castle Windsor