I have a class which I think makes more sense to make static, as it is basically a utility class. As a part of this class, I am interoping with Microsoft Access and Microsoft Excel.
Obviously, Office Interop objects are unmanaged resources, and a static class cannot have a destructor. I feel that it make sense to only have one instance of an Excel.Application
object, and one instance of an Access.Application
object that my various methods can make use of, taking care to close my databases and workbooks, and handle errors appropriately.
My issue comes when I close the program, if I don't run System.Runtime.InteropServices.Marshal.ReleaseComObject("myOfficeApplicationInstance");
, the Office instances hang around in my task manager. If I release the object while my application is running, then I can't use it again.
I'm not sure if that all made sense so some code is below:
using System;
using Excel = Microsoft.Office.Interop.Excel.Application;
using Access = Microsoft.Office.Interop.Access.Application;
namespace QWERTY
{
internal static class CreateReport
{
private static readonly Excel _excel;
private static readonly Access _access;
static CreateReport()
{
_excel = new Excel();
_access = new Access();
}
internal static void Performance(DateTime reportDate)
{
_excel.Workbooks.Open(@"C:\whatever.xlsx");
//Do stuff with Excel
_excel.Workbooks.Close();
_access.OpenCurrentDatabase(@"C:\whatever.accdb");
//Do stuff with Access
_access.CloseCurrentDatabase();
}
}
}
A few questions
- Am I right that this should be a static class?
- How do I deal with unmanaged resources when I am finished using a static class?