Castle Windsor: Change Lifestyle

Posted by

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 🙂