Search code examples
performanceinversion-of-controllinfu

LinFu IoC Best Practices on High Traffic Websites


We’re in the final stages of putting together a quite high traffic website (approx 6 million page impressions per week) and are using LinFu as the IoC container within the new architecture.

We have a pretty standard setup:

Web Layer
 |
IServices <- Services Implementation
 |
IDataRepository <- DataRepository Implementation
 |
DataBase

In the web layer, we have an instance of the LinFu ServiceContainer (a singleton in our implementation) that provides instances of Services objects as required by the pages. Each of the classes within the DataRepository assembly is also created in the same way (each Services constructor takes in the interfaces of DataRepository objects that it requires).

A quick example would be:

IWeatherServices
{
    Weather GetForecast();
    Weather GetPrediction();
}

[Implements(typeof(IWeatherServices))
WeatherServices(IWeatherForecastRepository, IWeatherPredictionRepository) : IWeatherServices
{
    // implementation of methods
}

(and similar functionality again for the DataRepository classes)

We’ve left the lifecycle type as the default at the moment (I believe this is PerRequest).

My main questions would be:

  • Should we be keeping the ServiceContainer as a singleton within the web app?
  • Should the LifecycleType on the implementing classes be kept as the default values?

I know this is a little open-ended but we're in the process of tuning during load testing so am very interested in the general opinion.


Solution

  • Having one instance of the container (thus a singleton) is a very common thing to do. However, prevent it from being called throughout the application. Instead, use constructor injection and let the container only resolve the top most objects. From looking at your example, I believe you are already doing this.

    The transient lifestyle (creating a new instance on each call to the container) is the simplest thing, and often the safest thing to do. The changes of having race conditions because of multi-threading are minimal. On the other hand, it is the worst performing lifestyle.

    Should you change the lifestyle? If your application is fast enough, I shouldn't bother. And if it isn't fast enough, you should find out if moving services to a singleton lifestyle has any effect. In other words, follow Rico Mariani's 10 rules for performance: measure, measure, measure, measure, measure, measure, measure, measure, measure, and measure :-)