Error sending email simultaneously with RazorEngine
We have a class library that parses email content using the RazorEngine and sends the email using the web API client.
We use it to periodically send newsletters with a console application. This works really well as it can send 50k + emails per day.
We also use it to send emails from our web application (for example, confirmation email after a user has created an account).
We are using a static method Razor.Parse()
.
About 13% of sent emails cause the following error.
Cannot access a disposed object Object name: 'TypeLoader', source : RazorEngine, stackTrace :
at RazorEngine.Templating.TypeLoader.CreateInstance(Type type)
in RazorEngine\\src\\Core\\RazorEngine.Core\\Templating\\TypeLoader.cs:line 55
at RazorEngine.Templating.DefaultActivator.CreateInstance(InstanceContext context)
in RazorEngine\\src\\Core\\RazorEngine.Core\\Templating\\DefaultActivator.cs:line 20
at RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate, Type templateType, Object model)
in RazorEngine\\src\\Core\\RazorEngine.Core\\Templating\\TemplateService.cs:line 131
at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName)
in RazorEngine\\src\\Core\\RazorEngine.Core\\Templating\\TemplateService.cs:line 435
It looks like multiple emails are being sent at once (other emails sent do not cause this error)
Any help would be greatly appreciated as we don't know where this is coming from.
source to share
We had the same error but on RunCompile
. After some experimentation, it turned out that we recreated RazorEngineService
for each letter from the same TemplateServiceConfiguration
. Although the latter is not IDisposable
, there is something in it.
Rebuilding TemplateServiceConfiguration
every time, right before creation RazorEngineService
solves the problem. However, reuse RazorEngineService
. Apparently, after you have deleted RazorEngineService
something in it is TemplateServiceConfiguration
also deleted.
So, if you send multiple emails, create both TemplateServiceConfiguration
and and for them RazorEngineService
, or create them once and reuse.
source to share