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:

public class PerWebRequestLifestyleOverrider : IContributeComponentModelConstruction
{
public void ProcessModel(IKernel kernel, ComponentModel model)
{
if (model.LifestyleType == LifestyleType.PerWebRequest)
{
model.LifestyleType = LifestyleType.Singleton;
}
}
}

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

var conatiner = new WindsorContainer();
container.Kernel.ComponentModelBuilder.AddContributor(new PerWebRequestLifestyleOverrider());
// Rest of your code

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


Posted

in

by

Comments

3 responses to “Castle Windsor: Change Lifestyle”

  1. Rahul Avatar
    Rahul

    Great tip. How do you feel windsor compares to autofac?

    Like

  2. [โ€ฆ] via Castle Windsor: Change Lifestyle โ€” Hi, Iโ€™m Ankit [โ€ฆ]

    Like

  3. Ankit Vijay Avatar

    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

A WordPress.com Website.