title: IDependencyResolver disposed twice in one request
body: <p>I have a rather complex <code>WebAPI2</code> project using <code>Owin</code> and Dependency Injection using <code>Unity</code>. I now do have a controller action that gets <code>MultipartContent</code> from the <code>Request.Content</code> that is then handed over to a service (created by DI) that temporarily stores this file to the hard drive of the server. This is needed because the service uses an external and native DLL that reads this file for some validation and conversion. So the external DLL additionally stores the converted file as well as the conversion result (as XML) in the same location. My service now reads the conversion result and returns that result. After that the temp files are deleted.</p>
  
  <p>Problem now is that the <code>Dispose()</code> method of my own <code>IDependencyResolver</code> is called twice during that operation which actually destroys stuff so that the next request also fails. For example I do get errors that the controller cannot be created as it has no parameterless constructor or an <code>ObjectDisposedException</code> on <code>System.Web.Http.HttpServer</code>. After that the DI container is properly rebuild and everything works fine. And so on. So every second request fails.</p>
  
  <p>So here is some code:</p>
  
  <p>Owin Startup</p>
  
  <pre><code>[assembly: OwinStartup(typeof(MyNamespace.Startup))]
  namespace myNamespace
  {
      public class Startup
      {
          public void Configuration(IAppBuilder app)
          {
              HttpConfiguration httpConfiguration = new HttpConfiguration();
              httpConfiguration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
              app.UseCors(CorsOptions.AllowAll);
  
              IUnityContainer container = new UnityContainer();
  
              // setup dependency injection
              container.RegisterType&lt;IFileConversionService, FileConversionService&gt;();
  
              UnityConfig.RegisterControllers(container);
  
              // register routes
              WebApiConfig.Register(httpConfiguration);
  
              // setup dependency resolver
              httpConfiguration.DependencyResolver = new MyNamespace.UnityResolver(container);
  
              app.UseWebApi(httpConfiguration);
          }
      }
  }
  </code></pre>
  
  <p>Well I don't think that there is anything special about that. As you can see I do not use the <code>GlobalConfiguration.Configuration.DependencyResolver</code> due to <code>Owin</code>.</p>
  
  <p>My DependencyResolver:</p>
  
  <pre><code>public class UnityResolver : IDependencyResolver
  {
      private IUnityContainer _container;
      private bool _disposed;
  
      public UnityResolver(IUnityContainer container)
      {
          if (container == null)
          {
              throw new ArgumentNullException("container");
          }
         _container = container;
      }
  
      public object GetService(Type serviceType)
      {
          try
          {
              return _container.Resolve(serviceType);
          }
          catch (ResolutionFailedException)
          {
              return null;
          }
      }
  
      public IEnumerable&lt;object&gt; GetServices(Type serviceType)
      {
          try
          {
              return _container.ResolveAll(serviceType);
          }
          catch (ResolutionFailedException)
          {
              return new List&lt;object&gt;();
          }
      }
  
      public IDependencyScope BeginScope()
      {
          var child = _container.CreateChildContainer();
          return new UnityResolver(child);
      }
  
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
  
      protected virtual void Dispose(bool disposing)
      {
          if (_disposed)
          {
              return;
          }
  
          if (disposing)
          {
              _container.Dispose();
          }
  
          _disposed = true;
      }
  }
  </code></pre>
  
  <p>Again nothing special about this, as it was just copied from one of the many examples in the web.</p>
  
  <p>Now the ControllerAction:</p>
  
  <pre><code>public async Task&lt;IHttpActionResult&gt; Upload()
  {
      if (!Request.Content.IsMimeMultipartContent())
      {
          throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
      }
  
      MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
      await Request.Content.ReadAsMultipartAsync(provider);
  
      IList&lt;MyFile&gt; uploadFiles = new List&lt;MyFile&gt;();
      foreach (var file in provider.Contents)
      {
          MyFile myFile = new MyFile
          {
              FileName = file.Headers.ContentDisposition.FileName.Trim('\"'),
              Data = await file.ReadAsByteArrayAsync()
          };
  
          uploadFiles.Add(myFile);
      }
  
      List&lt;ConversionResult&gt; result = new List&lt;ConversionResult&gt;();
      foreach(MyFile file in uploadFiles)
      {
          result.AddRange(_fileConversionService.ImportFile(file));
      }
  
      if (result!= null &amp;&amp; result.Count() == uploadFiles.Count)
      {
          return Ok(importedParts);
      }
  
      return BadRequest("One or more files could not be imported.");
  }
  </code></pre>
  
  <p>Now the service:</p>
  
  <pre><code>public IEnumerable&lt;ConversionResult&gt; ImportFile(MyFile myFile)
  {
      lock (_lock)
      {
          IEnumerable&lt;ConversionResult&gt; conversionResult = new List&lt;ConversionResult&gt;();
          try
          {
              string inputFile = SaveFileTemporarily(myFile);
              string inputFileExtension = Path.GetExtension(inputFile);
              string logFile = inputFile.Replace(inputFileExtension, ".txt");
  
              // check if the file can be validated/converted by the DLL
              if (ValidateFileExtension(inputFileExtension))
              {
                  // call external DLL that writes log file and converted file
                  ConvertFile(inputFile, logFile, inputFileExtension);
  
                  conversionResult = ParseLogFile(logFile);
                  if (!conversionResult.Any())
                  {
                      // no errors found
                      conversionResult.Add(ConversionResult.NoError);
                  }
              }
              else
              {
                  conversionResult.Add(ConversionResult.UnknownFileType);
              }
          }
          finally
          {
              Directory.Delete(GenerateTempSavePath(myFile), true);
          }
  
          return conversionResult;
      }
  }
  </code></pre>
  
  <p>In <code>SaveFileTemporarily()</code> the file is stored to some folder, actually a sub folder of the bin folder; e.g. <code>Directory.CreateDirectory(savePath);</code> and <code>File.WriteAllBytes(fullPath, data);</code></p>
  
  <p>By debugging that I found out that I always break twice in the <code>IDependencyResolver.Dispose()</code> function which is not the case for any other controller action. By commenting stuff in the service method <code>ImportFile()</code> I found out that this has to do something with the file operations. So when I completely remove the <code>System.IO</code> namespace from the service class I do not get that behavior and everything seems to be fine.</p>
  
  <p>I'm really lost at this now as I hunt this bug for several days now. Does anyone have an idea what the problem is?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>When using the API from a website I also often (but not always) get this error: <code>No 'Access-Control-Allow-Origin' header is present on the requested resource.</code> This leads to <code>CORs</code> which is also configured in the Owin Startup (<code>app.UseCors(CorsOptions.AllowAll);</code>).</p>
  
  <p>This all hints to a more or less random disposal/crash of the whole Owin app. After those errors the Owin Startup method is called again which should not happen. When does the Owin Startup is being called?</p>
  
  <p>When activating all Exceptions in Visual Studio (DEBUG -> Exceptions) I don't get anything...</p>
  
  <p><strong>UPDATE AND SOLUTION:</strong>
  Well I don't really know why, but the problem is solved. In the <code>ImportFile()</code> method of the service class is a call to <code>SaveFileTemporarily()</code>. This method uses a path that I searched in the constructor of the class:</p>
  
  <pre><code>string codeBase = Assembly.GetExecutingAssembly().CodeBase;
  UriBuilder uri = new UriBuilder(codeBase);
  string path = Uri.UnescapeDataString(uri.Path);
  _tempFilePath = Path.GetDirectoryName(path) + TempDirectory;
  </code></pre>
  
  <p>Now here is the problem. When I use</p>
  
  <pre><code>_tempFilePath = AppDomain.CurrentDomain.BaseDirectory + TempDirectory;
  </code></pre>
  
  <p>everything works fine.</p>
  
  <p>I guess it has to do something with the shadow-copying...</p>