I've been tasked with creating a file converter in an ASP.NET Core application. The conversion will be performed by LibreOffice, and I already have it in a working state (as simple as calling LibreOffice in headless mode with the proper parameters). I've also read that LibreOffice does not allow more than one instance in memory at the same time, so using a lock seems a good solution.
Prototyped code as follows:
public void ConvertDocument(string inputPath, Guid objId)
{
lock (_lock_obj)
{
//Console.WriteLine(objId);
try
{
var target_path = Path.Combine(Path.GetTempPath(), "Conversor");
if (!Directory.Exists(target_path))
{
Directory.CreateDirectory(target_path);
}
using (var p = new Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:\Program Files\LibreOffice\program\soffice.exe";
p.StartInfo.WorkingDirectory = target_path;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = $"--headless --convert-to pdf --outdir {target_path} \"{inputPath}\"";
p.Start();
p.WaitForExit();
}
}
catch (Exception ex)
{
//Console.WriteLine($"Error. Id: '{objId:D}', mensaje : '{ex.Message}'.");
}
}
}
The class that will implement this method will be injected into the controller.
My question is: should this class be injected as Singleton
? Or can it be injected as Scoped
without problems?
I've also read that LibreOffice does not allow more than one instance in memory at the same time
Just like this restriction, I think that on the server, only one instance can be running at the same time. So this class be injected as Singleton.
Reason
AddTransient, AddScoped and AddSingleton Services Differences
Scoped objects are the same within a request, but different across different requests.
If you use AddScoped
, many request can invoke soffice.exe
.
I think soffice.exe
is not the best choice for you.
Suppose you have 500 users, and one document needs to be processed for one minute. So only 60 users can complete their operations in one hour. This is very unreasonable.
I suggest that you use other three-party SDKs to meet more needs.
Convert Word doc and docx format to PDF in .NET Core without Microsoft.Office.Interop