UPDATE: This facility made its way into Castle Microkernel, with name OnCreateFacility. I also made it possible to specify more than one actions.
In one of Joshua Flanagan's recent post he mentioned about how they handle application configuration and I have to say that I liked their way. I also liked how SM can post-modify an object created, and looked for a way to do it in Castle. As many other stuff, I was able to achieve the same effect with a custom Facility.
If I go further in the details, I had to catch ComponentCreated event of Kernel.
public class EnrichWithFacility:AbstractFacility
{
public const string ExtendWithPropertyKey = "extendwith";
protected override void Init()
{
Kernel.ComponentCreated += Kernel_ComponentCreated;
}
void Kernel_ComponentCreated(ComponentModel model, object instance)
{
if(model.ExtendedProperties.Contains(ExtendWithPropertyKey))
{
var action = model.ExtendedProperties[ExtendWithPropertyKey] as ExtendComponentDelegate;
action(this.Kernel, instance);
}
}
}
Whenever a component is created, I will catch it and ask if there is any EnrichWith registered for the ComponentModel, and if there is any, invoke the action.
I also added a fluent registration extensions (Castle style!) in order to make it easy to register enrichments.
container.Register(Component.For<IService>().ImplementedBy<MyService>()
.EnrichWith((kernel, instance) => ((IService) instance).I++));
The code for the facility, fluent registration interface,and the tests can be found on our never-ending blog engine, BlogSharp codebase.
fe6b6031-8183-4713-b11b-7252d3ae1d2a|1|2.0
castle, windsor, microkernel