C# – Scope of static variables in ASP.NET sites

asp.netcnet

If running multiple ASP.NET applications in the same application pool, how many instances will I have of a class' static variable?

  1. One per application pool?
  2. One per application pool worker process?
  3. One per application?
  4. Something else?

Just to give some context:

I'm thinking specifically of a ServiceLocator implementation we have that holds a UnityContainer in a static class variable. The question is, will multiple apps registering a container on the ServiceLocator interfere with one another?

The apps are running in IIS 7.5 on .NET 4.0, should that make any difference.

Example code (simplified)

public static class ServiceLocator
    {
        private static IUnityContainer _container;

        public static void Initialize(IUnityContainer container)
        {
            if (_container != null)
            {
                throw new ApplicationException("Initialize should only be called once!");
            }
            _container = container;
        }

    }

If i run this from two different web applications which run in the same application pool, , typically in Application_Start, will it throw an exception on the second invocation? Will it always throw an exception? Will it never throw an exception? Will it throw an exception in some configurations?

UPDATE: I know there will be one instance of the static variable per application domain. So, the question could be rephrased to "If running multiple ASP.NET applications in the same application pool, how many App Domains will I have?"

I've been looking a lot around, but haven't found any authoritative references on this. Any help is appreciated, preferably with references to official Microsoft documentation.

Best Answer

If running multiple ASP.NET applications in the same application pool, how many App Domains will I have?

Each application pool can have multiple worker processes, each worker process will run different application instances. Each instance of an application has a separate AppDomain - so the answer to your original question is one per application instance.