private void Dispose(bool isDisposing)
        {
            if (_disposed)
            {
                return;
            }

            if (_appDomainProxy != null)
            {
                _appDomainProxy.RunCodeInAppDomain(() => HttpRuntime.UnloadAppDomain());
                _appDomainProxy = null;
            }

            DeleteTestBinaries();

            if (isDisposing && _enforceSingleInstance != null)
            {
                using (_enforceSingleInstance)
                {
                    _enforceSingleInstance.Release();
                    _enforceSingleInstance = null;
                }
            }

            _disposed = true;
        }
        public AspNetTestHost(string physicalDirectory, string virtualDirectory, TimeSpan timeout, Type appDomainProxyType)
        {
            if (!typeof(AppDomainProxy).IsAssignableFrom(appDomainProxyType))
            {
                throw new Exception(string.Format("Type: {0} should inherit from {1}", appDomainProxyType, typeof(AppDomainProxy)));
            }

            PhysicalDirectory = Path.GetFullPath(physicalDirectory);

            var security = new SemaphoreSecurity();

            security.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow));

            bool createdNew_notUsed;
            var  semaphoreName = "Global\\MvcTestingAspNetTestHost" + PhysicalDirectory.GetHashCode();

            _enforceSingleInstance = new Semaphore(1, 1, semaphoreName, out createdNew_notUsed, security);

            try
            {
                if (!_enforceSingleInstance.WaitOne(timeout))
                {
                    throw new Exception("Could not obtain semaphore: " + semaphoreName);
                }

                if (!Directory.Exists(PhysicalDirectory))
                {
                    throw new Exception("Could not find directory: " + PhysicalDirectory);
                }

                CopyTestBinaries();
                _appDomainProxy = (AppDomainProxy)ApplicationHost.CreateApplicationHost(appDomainProxyType, virtualDirectory, PhysicalDirectory);
                _appDomainProxy.RunCodeInAppDomain(InitHost);
            }
            catch
            {
                DeleteTestBinaries();
                using (_enforceSingleInstance)
                    _enforceSingleInstance.Release();
                throw;
            }
        }