Archive for the ‘Windsor’ Category

Windsor: Component Burden described as a (bad) side effect

February 26th, 2008

This blog entry is fantastic. It explains how Windsor (well, MicroKernel) deals with non-singletons that are disposable. In the end, the author makes an interesting test:

public class DisposableCon : IDisposable {
   public ITest ITest;
   public DisposableCon(ITest iTest) {
      ITest = iTest;
   public void Dispose() {

This class simply declare a Constructor dependency, and implements IDisposable, but in the dispose does not do any stuff. The following test shows you that the container does not keeps a reference nor dispose the inner ITest object.

DisposableCon tran;
using (WindsorContainer ioc = new WindsorContainer(new XmlInterpreter(“config1.xml”))) {
   tran = ioc.Resolve(“TransientDisposableCon”);

So it is your duty to be sure that the inner objects injected by the container will be disposed correctly.

So this behavior is wrong! WRONG! You should not have to care about releasing the dependencies yourself, the container should keep track of them.

Explaining again. Suppose you have the following components:


Services depends on DependencyA, which depends on DependencyB. Let’s consider that all of them are transients.

When the “Service” is requested from the container, Windsor creates the dependencies in the bottom-top order:

1. Create DependencyB
2. Create DependencyA
3. Create Service

Service can be returned.

In an ideal world, when Service is released (container.Release(service) or container.Dispose()), Windsor needs to release all of them in the inverse order:

1. Dispose Service
2. Dispose DependencyA
3. Dispose DependencyB

DependencyA is the “burden” of Service. DependencyB is the “burden” of DependencyA. That’s what I call Component Burden. The container being able to keep track of these things that need to be release.

Of course, for 90% of the container usage, you’d use singletons, so that’s why the component burden – which is missing on Windsor and maybe on every other IoC container out there – is not missed that much. It’s only required for non-singletons components that have a decommission phase (for example, Disposable ones).

Anders has started working on this back in March of 2007. He renamed it to component responsability. The implementation wasn’t ideal, so I started reviewing it before applying. Never found the time to finish.

So, if you really want to dig into the internals of the MicroKernel, figure out an optimal strategy that will keep the “burden” only when necessary, make it beautiful, test it, license it as ASL 2.0 and send it to us, we would greatly appreciate it :-)

Registering components on Windsor, the cool way

February 25th, 2008

Craig Neuwirt (no blog), one of the oldest Castle committers (I mean, he has been involved for a long time!) created a sweet way to register components on Windsor. I’ve been planning to blog about it for a long time, but I wanted to get some experience with it before.

So we basically provide this old fashioned family of methods:


The AddComponentWithProperties is mislead. It means that you’re going to provide the custom properties for the components, those that are used by facilities and/or subsystems. Not the actual properties of the implementation.

Now, Craig added a simple Register method. The magic happens on the build you pass to the Register method:

container.Register( Component.For<IMyServiceContract>().ImplementedBy<MyServiceImpl>() );

As the Register accepts an array (with ParamArray attribute), you can use to make multiple registrations:


I’m sure you want more. And you got it. The Component.For creates a ComponentRegistration instance. See its source to see that it does everything you can do through external configuration.

More examples:

Specifying the name and a lifestyle:

container.Register( Component.For<IMyServiceContract>().

Adding a custom instance

container.Register( Component.For<IMyServiceContract>().
	Instance(new MyServiceImplementation() )

Setting up parameters:

container.Register( Component.For<IEmailSender>().
		Parameter.ForKey("port").Eq("155") )

Setting up service overrides:

container.Register( Component.For<ISpamSender>().
		ServiceOverride.ForKey("emailSender").Eq("smtpsender") )

Now, the only weakness left to cover on Windsor is the damn Component Burden. Once it’s done, we’re ready to 1.0.

Why I don’t like AMC

February 9th, 2008

Just making clear before someone thinks I have some personal vendetta with Aaron. What I dislike about the Auto Mocking Container is that it takes out the clarity of the test. I’d rather mock the services I need, and only those, on my test method or on my SetUp method. That makes clear to whoever is reading what I’m testing, the services I’m using and so on.

And to tell you the truth I rarely use an IoC container on my test cases anyway.

donjon – a teaser

January 20th, 2008

A picture still worth a thousand words.


Some more information about Castle, and why we are not 1.0

March 18th, 2007

As Castle, a more than two years old project, is getting some deserved buzz, it’s a good thing to come on public and say “hey, it’s not perfect”. And I think I might be the best person to let you know what is wrong or missing with it. The good thing about OSS compared to commercial products is that nothing stop us from saying the limitations and problems. I’ll leave the comparison with other company’s strategies as an exercise to the reader.

First, what Castle Project is all about? To fully explain that, I have to give you some more information about my life.

A long long time ago, in a distant galaxy

Back to 2003 when I was a member of the Apache Avalon project I had my view of what could be a close-to-perfection IoC container. In my view it should be minimalist and yet be so easily extensible that it could handle situation we would never anticipate. That is far different from what Avalon, Hivemind and Spring tries to be. Around that time I read The Pragmatic Programmer and the orthogonality concept made a lot of sense to me, that was the almost mathematical design that should be applied to this new container.

Apache Avalon was closed due to a very disruptive community, I’ve sadly resigned from it, and a new project was started: Apache Excalibur. Again I was excited, but the community settled to be a supportive community instead of riding the tide and provide a killer IoC container to the Java community, we had the brains, we had the vote of confidence from Apache. I engaged into endless discussion about this new direction, but I can’t change the world, can I?

September of 2004 I went to London to study english and had an interview at ThoughtWorks. Met some great guys on Geek Nights, some of them I still in touch today. Was reject from ThoughtWorks because I used “final” on my variables (something that was on the guideline for Apache’s projects) and couldn’t agree that my interviewer refactorings made the code flow better (and I still can’t). So if you’re applying for TW remember to swallow your opinion and just nod, there are some very inflated egos there.

Back in Brazil, October of 2004, I was zen. Decided to sell my car and work and study on what I wanted. My passions haven’t changed since then. AI, compilers, transaction management and IoC containers. Founded Castle to provide this IoC container I have been writing for almost two years. In the meantime I was also introduced to Ruby on Rails and decided to create something for real using it. It was distant from 1.0 at the time, and I had a large amount of problems. .Net provided a much richer API than Ruby. While there was Ruby projects to fill the gap, they weren’t mature, and making everything work wasn’t easy, especially on Windows. The performance wasn’t something thrilling too. Nevertheless the simplicity offered by RoR could not be ignored.

I’ve written a book on ASP.Net WebForms, so it was hard to admit that it didn’t work as nicely as RoR. Relying on WebForms in a real, complex system led to major headaches. At this point I decided to broad Castle’s ambitious and provide a complete development stack. The major goal was to simplify our life. That was the itchy I tried to scratch: simplification.

Due to my experience on Apache Avalon I also knew what not to do to create a healthy community. Though I’ve made a lot of mistakes, I can be proud of the community fostered around Castle.

IoC and the .net camp

Though my article on Castle was well received, I understood that the .net camp wasn’t ready for IoC containers. It was wrong to push it if people are not prepared to see the benefits, and just see it as a burden (damn, I have to register components, what is that for?). I can still remember the angry reviews on blogs and blogs comments all around.

The MicroKernel (and Windsor) are the projects I most proud of, and still the projects that receive less attention. Some things that were there since the first SVN commit received some attention last week (ie interceptors support). Seems that MS has to push something to have people realizing what IoC containers are for, what interceptors could do. Having to wait for this MS pushes is kind of depressing.

Castle and the Stronghold

After being requested for consulting a few times, I decided to open a business to offer Castle related support, development and consulting. We received so many requests that shortly I had to start rejecting development and consulting requests. The good thing is that developing for so different project scenarios bring to the surface many weakness on Castle, which were fixed to proceed with the development.

That’s how the validation support came to the surface, many view components and bug fixes. The current documentation state was created in a way that we could use it, instead of always checking the source code. While this is an improvement I admit that it still lacking documents.

Offering a ‘throat to choke’ is also a good way to lowering the barriers for adoption. We know that some companies won’t embrace anything unless there’s an entity behind it that can be sued in the event of any problems.

What is missing

OSS projects have a different life cycle compared to commercial or products. On Castle we make a release and then start to implement all crazy ideas that were voiced. Stabilize the code and repeat.

Some things, in my perception, stop us from releasing a 1.0. As you will see there aren’t many, and I’m trying do decide if we should work on them now and release a 1.0, or release another Candidate and continue to work on the missing pieces.

The Component Burden, on the MicroKernel

This is somewhat difficult to explain, but stay with me. Every time you request a component from the container it might have dependencies on components with different lifestyles. For example, you might request a component that is transient, and depends on transient and pooled instances.

Today you can release the transient (root) instance, but the dependencies won’t be properly released. This is a major limitation, but fortunately 99% of scenarios do not depend on this. Anyway this is not an excuse to not implement this support.

Btw, when I say properly release, what I mean is the decommission steps won’t run and the component will not be returned to the lifecycle manager. For pooled components that means that it wont returned to the pool. Components that implement IDisposable wont have the Dispose being invoked by the container. But rest assured that the container will not hold instances creating a memory leak.

Container Scopes

Another complex usage of containers and very useful for complex situations were components (and possibly business logic) can vary depending on some external factor. The idea is to create an hierarchy of containers. The top level container contains the invariant components, or the system core. Lower in the hierarchy you’ll find container specifically set for a client, or for a host name, or for anything that indicates the necessity of a different set up.

While I’m involved with at least three projects that will require this support at some point, I still don’t have enough use cases to implement it right. Bill Pierce has implemented almost everything required, though, but there are some issues on the backlog to be resolved.

Validator component and ActiveRecord validation infrastructure

We have to drop AR validation infrastructure in favor of the new validation component. No point in maintaining two.


While AR can make you map your database in no time, it also leads to a Domain Model that is tightly coupled with your entities on the database. Sometimes this is a big problem, so careful when adopting it on an app that will ask for a richer domain model.

MonoRail’s controller testability

The TestSupport component offered by MonoRail is totally flawed. It is useful for us, as we can use it to test how MonoRail is correctly integrated with the ASP.Net API, but it useless for any enterprise project.

The approach Aaron explains on his blog is a good way to test controllers, and I think MonoRail should offer something like that out of the box. I tried to refactor it last night to accomplish that. I gave up.

I should have used TDD to code MonoRail. Using that small time window (getting home after work, dining in front of the computer while coding changes) unsurprisingly does not create the best design. That is something I can only fix on MonoRail 2.0, or with a heavy refactoring. I’m still thinking about it…

NVelocity and Brail view engines could be better

We could work on a pre-processor that could translate more pleasant constructions into method calls or directives.

I for one dislike the usage of view components from NVelocity, but there isn’t another way to integrate it with their AST. A new view engine is being considering for a long time. IronPython view engine is also on the backlog.

View component parameters bindings

Grabbing and converting data from the ComponentParams dictionary is boring. We need a way to wire this data directly to view component’s properties.


While we have a project generator, it is not enough. Creating complex html forms is repetitive. If you have the object the form should fill, we can have the computer generating the form. You can make a change here and there, and this is something I’m working on. Marc-Andre has created a Rails-like generator, and we would like to merge it with the VS.Net add in generator. Not an easy task, though.

ActiveWriter solves the ActiveRecord generation and in a divine way.

Support for .net 1.1

This is something that was requested and with some heat, but the way DynamicProxy 2 was coded makes it an almost impossible task. I’m considering dropping this support, even if that will turn some users into enemies. :-(

We tried to do it last Friday, gave up. I tried yesterday and got sick..

As you see, lots of issues to take care of, and it’s always an opportunity to consider getting involved with Castle. Rest assured it’s an experience where everyone learns a lot.

Web Client Software Factory vs MonoRail

March 15th, 2007

David Hayden asks “Can MonoRail compete with WCSF?”. I’d rather say “Can WCSF compete with MonoRail?” ;-)

A fair analysis would require a deep understanding of both projects. I’ll investigate WCSF in a near future, but for now, I’ll just give David some clues about some MonoRail features, as he lists what WCSF is going to support:

- Data-Drive UI: I’m not sure exactly what he meant by that. I can say that MonoRail has scaffolding support and a combination of FormHelper/DataBindAttribute is enough to save you a good number of repetitive lines of code.

- Validation: Castle has the Castle.Component.Validator, and MonoRail is fully integrated to it. This screencast might explain it a little better.

- UI Responsiveness: is that Ajax? MonoRail just relies on prototype to offer ajax support, although you can use any library you want. MonoRail also supports JS generation for more complex scenarios.

- Complex workflows: not sure what that means. As Ayende pointed out, we have wizard support.

On top of that, if you know what you’re doing, you can enable Windsor integration. That means that MonoRail will use Windsor to resolve Controllers, ViewComponents and Filters (optionally). So you gain all facilities and features offered by Windsor on your MR project. If you don’t like Windsor, you can even use Spring.

And last but not least, Castle is an OSS project with a strong community behind. Want to ask us “why did you implement this way and not some different way?”, join the list. Bumped into a bug, check our issue tracker. Want to ask a lightweight question, check our forum. And if you show commitment to the project, you will gain access to our SVN. While for some these might be not important things to reason, it’s clearly becoming something to pay attention for a growing number of people.

Update: Brian has used both, and shared his thoughts.

Windsor container and “environments”

February 12th, 2007

I bumped into a challenge today that might be of interest to others. We wanted to have a single web site project, and use it to run tests and to the usual development. During development it should use the standard devel database, for test cases, it should use the Test database which is always dropped/re-created by the test cases.

The problem is that we only have one web.config, and one setting for the connection string. Fortunately the connection string is kept by Windsor, in a properties.config but we couldnt think of a way to signalize the environment to it (test/devel).

Our solution was to create a new entity on Castle Windsor’s: IEnvironmentInfo. This interface allows a programmer to return the environment’s name based on, well, anything he wants. In our case we use IIS and VS.Net’s web server. The latter for standard development, the former to run the test cases. We could then use the web server port to distinguish the environment. If the application is running on 80 (IIS) it is being tested, otherwise it’s just a developer working on it.

Whatever is returned by IEnvironmentInfo is transformed into a define to Windsor’s configuration. So you can have

<?if devel ?>
<?else?> <!-- this is for test -->

In our case we have:

public class WebEnvironment : IEnvironmentInfo
    private readonly HttpApplication app;

    public WebEnvironment(HttpApplication app)
    { = app;

    public string GetEnvironmentName()
        return app.Context.Request.Url.Port == 80 ? "test" : "devel";

And all we have to do is pass that to Windsor when we instantiate it:

container = new WindsorContainer(new XmlInterpreter(), new WebEnvironment(this));

This might make no sense at all if you havent faced the challenge yet, but make sure you re-read this post when it clicks for you ;-)

Using events to reduce coupling and increase flexibility

February 4th, 2007

Those who know me are aware that I’m a big fan of the service pattern and domain objects (usually with a pinch of ActiveRecord), and I think that the Repository is the most overrated pattern nowadays. So now you know where I came from.

I was asked to disclose more information of something I mentioned lots of times on Castle Project list and also explained on Cuyahoga development mailing list, which is the use of events in order to decrease coupling and as a consequence maximize flexibility and extensibility. This is something that is rarely used even on Java camp, but when it’s used, they create some really cool stuff (wanna an example? Check SEDA and Apache Directory)

The goal is to have main players of your application firing notifications about important things that have just happened on it. On Java you’d use mostly interfaces or some magic with reflection, or embed a scripting engine like Rhino or Jython. On .net you have the option to use plain events, but the other options apply as well.

Now being pragmatic, when this kind of architecture is useful? IMHO it’s useful when you have non-related process that should take place in response to something that happened on the system. Last year I was porting an application that was complex as it had to deal with a legacy database and a new database. The authentication service authenticated the user using the legacy database, and if that passed we have to ensure a compatible token existed on the new database. Was that a task for the authentication service? Not at all (remember Separation of Concerns?).

So when an user successfully logged in, an UserLoggedIn notification was broadcasted. One of the components listening to this notification was the EnsureTokenExists process, which handled the existence of the user on the new database. Henry and Rafael (the guys at Stronghold) have told me about a system they designed that processed trading orders from a variety of data sources and relied on events to attach different processes/validations before committing the trade.

On the system I’m working on, an user that signs in is also translated into an event, along a lot of different notifications. This is specially significant to centralize, for instance, logging, email sending and data replication.

It’s important that you do not rely on event ordering, though. If your application do need to rely on event ordering, then you’d need to build and manage a pipeline. This is a little bit more sophisticated, but easily achievable.

A practical example

Consider a standard e-commerce application. Suppose we have a payment service. Its goal is to perform some business rules and delegate the payment processing to the payment method selected (paypal, credit card, ACH). Nothing more, nothing less.

Now we to send confirmation emails, send failures notices to the site administration and update some statistics based on the payment process result. All of this certainly does not belong on the payment service. My approach is to create a notification for the payment service. You might consider creating just a big notification service for the whole application, but this might lead to graph cycling (you’ve been warned).

We can use a common term to define the source of events (the publisher) and the consumers (the subscribers). The service notification service is the publisher, and we can create three subscribers: PaymentEmailSubscriber, PaymentFailureSubscriber and PaymentStatisticSubscriber.

Here is how the notification service might look like:

public interface IPaymentNotificationService
    void FirePaymentSucceeded(IPaymentMethod method, RegisteredUser user);
    void FirePaymentFailed(IPaymentMethod method, RegisteredUser user, Exception ex);

    event PaymentNotificationHandler PaymentSucceeded;
    event PaymentErrorNotificationHandler PaymentFailed;

And the subscribers:

public class PaymentEmailSubscriber
    public void OnPaymentSucceeded(IPaymentNotificationService notificationService, PaymentNotificationArgs args)
        Console.WriteLine("Sending email to user notifying about successful transaction");

public class PaymentFailureSubscriber
    public void OnPaymentFailed(IPaymentNotificationService notificationService, PaymentErrorNotificationArgs args)
        Console.WriteLine("Sending email to Admin about transaction failure");

public class PaymentStatisticSubscriber
    public void OnPaymentSucceeded(IPaymentNotificationService notificationService, PaymentNotificationArgs args)
        Console.WriteLine("Statistics: one more successful payment");

    public void OnPaymentFailed(IPaymentNotificationService notificationService, PaymentErrorNotificationArgs args)
        Console.WriteLine("Statistics: one more failed payment");

Finally, the payment service:

public class PaymentService
    private readonly IPaymentNotificationService notificationService;

    /// <summary>
    /// Initializes a new instance of the <see cref="PaymentService"/> class.
    /// </summary>
    /// <param name="notificationService">The notification service.</param>
    public PaymentService(IPaymentNotificationService notificationService)
        this.notificationService = notificationService;

    /// <summary>
    /// Process payment
    /// </summary>
    /// <param name="method">The payment method.</param>
    /// <param name="user">The registered user instance.</param>
    public void Pay(IPaymentMethod method, RegisteredUser user)
            if (user.IsBlocked)
                throw new PaymentException("Cannot proceed checkout as the user is blocked");

            if (!method.IsValid())
                throw new PaymentException("Payment information refused by third party. " + 
                                           "Please review the information");


            notificationService.FirePaymentSucceeded(method, user);
        catch(Exception ex)
            notificationService.FirePaymentFailed(method, user, ex);


Note how the design got very simple with almost no effort, you can plug subscribers to handle new requirements easily.

You can download the EventSample1 to study it in more detail. Note that I’m not using an IoC container here, just to keep things as simple as possible. The wiring is taking place in the application start up:

public static void Main()
    // Configure application (wire everything)

    IPaymentNotificationService notification = new DefaultPaymentNotificationService();

    PaymentEmailSubscriber subscriber1 = new PaymentEmailSubscriber();
    PaymentFailureSubscriber subscriber2 = new PaymentFailureSubscriber();
    PaymentStatisticSubscriber subscriber3 = new PaymentStatisticSubscriber();

    // subscribing

    notification.PaymentSucceeded += new PaymentNotificationHandler(subscriber1.OnPaymentSucceeded);
    notification.PaymentFailed += new PaymentErrorNotificationHandler(subscriber2.OnPaymentFailed);
    notification.PaymentSucceeded += new PaymentNotificationHandler(subscriber3.OnPaymentSucceeded);
    notification.PaymentFailed += new PaymentErrorNotificationHandler(subscriber3.OnPaymentFailed);

    PaymentService paymentService = new PaymentService(notification);


Using Windsor and the Event wiring facility

Windsor Container can simplify the wiring for you if you use the Event wiring facility. In this case the initialization code will be simplified:

WindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource()));

And the configuration file:


    <facility id="event.wiring" 
          type="Castle.Facilities.EventWiring.EventWiringFacility, Castle.MicroKernel" />


    <!-- Subscribers -->

    <component id="email.subscriber" 
           type="EventsSample2.Subscribers.PaymentEmailSubscriber, EventsSample2" />
    <component id="failure.subscriber"
           type="EventsSample2.Subscribers.PaymentFailureSubscriber, EventsSample2" />
    <component id="statistics.subscriber"
           type="EventsSample2.Subscribers.PaymentStatisticSubscriber, EventsSample2" />

    <!-- Notification service -->

    <component id="payment.notification.service"
           service="EventsSample2.IPaymentNotificationService, EventsSample2"
           type="EventsSample2.DefaultPaymentNotificationService, EventsSample2" >
        <subscriber id="email.subscriber" 
        <subscriber id="failure.subscriber" 
        <subscriber id="statistics.subscriber" 
        <subscriber id="statistics.subscriber" 

    <!-- Services -->

    <component id="payment.service"
           type="EventsSample2.PaymentService, EventsSample2" />


Again, a sample is available if you want to download it.

Final thoughts

As with any pattern, do not overuse it. Again: do not overuse it. I only rely on it when I’m about to write code that is unrelated to the primary concern of a class. An authentication service should not be concerned about legacy and non-legacy database. That’s the line, and the good judgment shall lead you to the right path.

Hope you enjoyed the reading. Cheers!