views:

166

answers:

1

Hi,

It is very common to create Dependency Injection container for the ASP.NET application so it lives while the application lives.

I create the DI container in each request and release it at the end of the request.
The main purpose is that any DI container supports Disposing objects when the container gets disposed.


Additional: If I need to share resources among requests (NHibernate SessionFactory) I just keep them in a static variable and encapsulate that value in an object per request. Like this:

public class SessionFactoryAggregator : ISessionFactory {
    static ISessionFactory actualFactory;

    // Implement ISessionFactory and proxy calls to the actualFactory
}

This is just simulated singleton pattern.


My questions:

  1. Is it ok to do that?
  2. If not why and what should be done instead?
  3. Any known performance issues in this approach?


Update: At the moment I use Castle Windsor through my own abstraction of DI provider, so the actual container is pluggable.

Thanks.

+1  A: 

If it works for you, then it is OK :)

Because of the stateless nature of web applications, doing this should not give you any functional problems, because you are simply going to have a container per request, and the multiple instances will simply live independently of each other.

From a scalability perspective, however, this may not be the most efficient approach (but remember that you should measure performance instead of guessing), as the application will be wiring up and tearing down a lot of resources that might just as well have been shared.

Most DI containers have the ability to manage object lifetime, and most of them are even web-aware, which means that you should be able to tell it that certain components have a "per-request" lifetime and that they should be disposed after each request.

That would allow you to keep other components alive as Singletons (the lifetime pattern, not the creational pattern) so that they can be shared among multiple request. This can often be a good idea for Data Access components that are typically thread-safe since they hold no mutable state.

Mark Seemann