Prechádzať zdrojové kódy

Added Dispose to ExcelDynamicWriter, #5

Piotr Czajkowski 2 mesiacov pred
rodič
commit
840d4d3778

+ 17 - 2
ExcelORM/ExcelORM/ExcelDynamicWriter.cs

@@ -4,7 +4,7 @@ using ExcelORM.Models;
 
 namespace ExcelORM;
 
-public class ExcelDynamicWriter
+public class ExcelDynamicWriter : IDisposable
 {
     private readonly IXLWorkbook xlWorkbook;
     public ExcelDynamicWriter(string? path = null)
@@ -74,5 +74,20 @@ public class ExcelDynamicWriter
     {
         xlWorkbook.SaveAs(path);
         converter?.MakeCompatible(path);
-    } 
+    }
+
+    public void Dispose()
+    {
+        Dispose(true);
+        GC.SuppressFinalize(this);
+    }
+
+    protected virtual void Dispose(bool disposing)
+    {
+        if (disposing)
+        {
+            xlWorkbook?.Dispose();
+        }
+    }
+    ~ExcelDynamicWriter() => Dispose(false);
 }

+ 3 - 3
ExcelORM/ExcelORMTests/DynamicWriterTests.cs

@@ -18,7 +18,7 @@ public class DynamicWriterTests
         var results = reader.Read().ToArray();
         Assert.NotEmpty(results);
 
-        var writer = new ExcelDynamicWriter();
+        using var writer = new ExcelDynamicWriter();
         writer.Write(results);
         writer.SaveAs(testFile);
 
@@ -41,7 +41,7 @@ public class DynamicWriterTests
         var results = reader.ReadAll().ToArray();
         Assert.NotEmpty(results);
         
-        var writer = new ExcelDynamicWriter();
+        using var writer = new ExcelDynamicWriter();
         writer.WriteAll(results);
         writer.SaveAs(testFile);
 
@@ -65,7 +65,7 @@ public class DynamicWriterTests
         Assert.NotEmpty(results);
 
         using var writeWorkbook = new XLWorkbook();
-        var writer = new ExcelDynamicWriter(writeWorkbook);
+        using var writer = new ExcelDynamicWriter(writeWorkbook);
         writer.Write(results);
 
         using var savedReader = new ExcelDynamicReader(writeWorkbook);