From 2e761415e48fb6fca264b41f133cd968356da39e Mon Sep 17 00:00:00 2001 From: Martin Costello Date: Fri, 13 Apr 2018 17:30:33 +0100 Subject: [PATCH] Implement IDisposable for derived types for WebApplicationFactory (#7637) * Implement IDisposable for derived types for WebApplicationFactory Add a protected Dispose method and a finalizer to WebApplicationFactory for use in classes that derive from it and want to dispose of their own resources. Resolves #7631. * Address review feedback Only dispose of fields if disposing is true. --- .../WebApplicationFactory.cs | 44 ++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.AspNetCore.Mvc.Testing/WebApplicationFactory.cs b/src/Microsoft.AspNetCore.Mvc.Testing/WebApplicationFactory.cs index 3ae20c1b60..910db78d92 100644 --- a/src/Microsoft.AspNetCore.Mvc.Testing/WebApplicationFactory.cs +++ b/src/Microsoft.AspNetCore.Mvc.Testing/WebApplicationFactory.cs @@ -20,6 +20,7 @@ namespace Microsoft.AspNetCore.Mvc.Testing /// Typically the Startup or Program classes can be used. public class WebApplicationFactory : IDisposable where TEntryPoint : class { + private bool _disposed; private TestServer _server; private Action _configuration; private IList _clients = new List(); @@ -54,6 +55,14 @@ namespace Microsoft.AspNetCore.Mvc.Testing _configuration = ConfigureWebHost; } + /// + /// Finalizes an instance of the class. + /// + ~WebApplicationFactory() + { + Dispose(false); + } + /// /// Gets the created by this . /// @@ -327,17 +336,40 @@ namespace Microsoft.AspNetCore.Mvc.Testing /// public void Dispose() { - foreach (var client in _clients) + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + /// + /// to release both managed and unmanaged resources; + /// to release only unmanaged resources. + /// + protected virtual void Dispose(bool disposing) + { + if (_disposed) { - client.Dispose(); + return; } - foreach (var factory in _derivedFactories) + if (disposing) { - factory.Dispose(); - } + foreach (var client in _clients) + { + client.Dispose(); + } - _server?.Dispose(); + foreach (var factory in _derivedFactories) + { + factory.Dispose(); + } + + _server?.Dispose(); + } + + _disposed = true; } private class DelegatedWebApplicationFactory : WebApplicationFactory