Castle Windsor: Change Lifestyle

In my current project, we use Castle Winsdor for Dependency Injection. I must admit before this project I had never used or even heard of it. I have had some love-hate relationship with Castle Windsor , with more hate than love initially. However, over a period of time, I realized that Castle Windsor is probably among the best IoC containers out there. It is extremely flexible and powerful.

Recently, I got stuck with up an issue where Integration Test Cases of our application started failing. It took me some time to find out the root cause of the issue.

Why were Integration Test Cases failing?

We use ASP.NET Web API self Host for our integration test cases and had shared code to register components to WindsorContainer . Few of these components were PerWebRequest lifestyle components. Web API Self Host did not like PerWebRequest lifestyle and started throwing Internal Server Error (500)

Of course, the easiest solution was to use separate code to register the containers for Integration test cases and register PerWebRequest components as Singleton in integration tests. However, that would mean that we would need to have two identical copies of the same code. It would be a maintenance headache. While searching for a solution I came across this article which talked about IContributeComponentModelConstruction.

IContributeComponentModelConstruction is the easiest way of extending and modifying Windsor container. You can implement this interface to override component lifestyle.

Here is the usage:

Now, you can plug the above code to your container by simply adding to below line of code while registering your Windsor Container:

Hope this helps you to save some debugging effort πŸ™‚

Advertisements

3 thoughts on “Castle Windsor: Change Lifestyle

  1. Hi Rahul. Glad that you like it. Well, autofac is definitely more popular these days. it is considered modern container as compared to Castle Windsor. If I start a new project today, I might consider using Autofac over Castle Windsor. Having said that, Castle Windsor is actively maintained and updated in GitHub as well. So, you are not making a wrong choice choosing Castle Windsor as your IoC container πŸ™‚

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s