I have an extension method on the HttpApplicationState object for getting my IoC container out of the application. This same code will also create the container if it doesn’t exist.
I have 2 questions:
- Is my code actually thread safe as I intend it to be
- Is this considered the best practice for dealing with the application state
Code as follows:
private const string GlobalContainerKey = 'UnityContainerKey'; public static IUnityContainer GetContainer(this HttpApplicationState application) { var container = application[GlobalContainerKey] as IUnityContainer; if (container == null) { try { application.Lock(); container = application[GlobalContainerKey] as IUnityContainer; if (container == null) { container = new UnityContainer(); application[GlobalContainerKey] = container; } } finally { application.UnLock(); } } return container; }
You need to put
in the lock as well, otherwise many threads may create a new container in sequence.