Interoperabilidade do Office não funciona no serviço do Windows

Eu tenho um problema muito estranho com o Microsoft Office.

Eu tenho uma biblioteca comum cuja única finalidade é abrir qualquer tipo de arquivo de documento do Word é passado para ele (por um caminho de arquivo completo ...) e salvar o documento do Word aberto como um arquivo pdf.

O problema estranho é que, se eu consumir essa biblioteca de um serviço do windows, sempre que ela tentar abrir o documento do word, eu recebo um null ... aka, o documento do word nunca foi aberto.

No entanto, se eu consumir a biblioteca de um aplicativo WPF ou Windows Form, nunca tenho problemas. Estou ciente de que existem problemas com segmentação, (Single Thread Appartment) no entanto eu não tenho idéia de como corrigi-lo para trabalhar fora do serviço do Windows. :( :( :(

Eu apreciaria qualquer ajuda! O erro que recebo é o seguinte:

Mensagem de exceção: {"Referência de objeto não definida para uma instância de um objeto."} (Referindo-se ao documento do word). Exceção Interna: Nulo; HResult: -2147467261. Dados: ListDictionaryInternal com 0 entradas; Rastreamento de pilha: em DocumentConverter.ToPdf (String currentWorkingFolderPath, String pathToDocumentToConvert) em c: \ Arquivos de projeto ... \ DocumentConverter.cs: linha 209

Então aqui está a função de biblioteca. Ele requer a referência do Microsoft Office, que é criada pelo Visual Studio Tools for Office.

private string ToPDF(string currentWorkingFolderPath, string pathToDocumentToConvert)
{
    string temporaryPdfFolderPath = Path.GetFullPath(currentWorkingFolderPath + "\\pdf\\");
    string temporaryPdfFilePath = Path.GetFullPath(temporaryPdfFolderPath + "\\pdffile.pdf");

    if (!FileSystem.CreateDirectory(temporaryPdfFolderPath))
    {
        return null;
    }

    try
    {
        Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();

        object objectMissing = System.Reflection.Missing.Value;

        wordApplication.Visible = false;
        wordApplication.ScreenUpdating = false;

        FileInfo wordFile = new FileInfo(pathToDocumentToConvert);

        Object fileName = (Object)wordFile.FullName;

        // This is where it breaks when called from windows service. Use the dummy value as a placeholder for optional arguments
        Document wordDocument = wordApplication.Documents.Open(ref fileName, ref objectMissing,            
            true, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,            
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,            
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);



        object outputFileName = (object)temporaryPdfFilePath;
        object fileFormat = WdSaveFormat.wdFormatPDF ;

        // Save document into PDF Format
        wordDocument.SaveAs(ref outputFileName,
            ref fileFormat, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing,
            ref objectMissing, ref objectMissing, ref objectMissing, ref objectMissing);

        // Close the Word document, but leave the Word application open.
        // doc has to be cast to type _Document so that it will find the
        // correct Close method.                
        object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
        ((_Document)wordDocument).Close(ref saveChanges, ref objectMissing, ref objectMissing);

        wordDocument = null;

        // word has to be cast to type _Application so that it will find
        // the correct Quit method.
        ((Microsoft.Office.Interop.Word._Application)wordApplication).Quit(ref objectMissing, ref objectMissing, ref objectMissing);

        wordApplication = null;

    }
    catch (Exception ex)
    {
        //logging code
        return null;
    }

    return temporaryPdfFilePath;
}

questionAnswers(5)

yourAnswerToTheQuestion