I am getting a System.ObjectDisposedException
when i try to send an e-mail in a .NET core 6.0 project using the fluent-email library:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mail.SmtpClient'.
at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)
at FluentEmail.Smtp.SendMailEx.SendMailExImplAsync(SmtpClient client, MailMessage message, CancellationToken token)
I have tried to inject the smtpclient
transient, scoped and as a singleton but neither one of the options fixed this issue.
DI code:
var smtpClient = new SmtpClient(smtpSenderOptions.Host, smtpSenderOptions.Port)
{
EnableSsl = smtpSenderOptions.EnableSsl
};
services.AddSingleton(instance => smtpClient);
Usage (from the fluent-email library (https://github.com/lukencode/FluentEmail)):
// Taken from https://stackoverflow.com/questions/28333396/smtpclient-sendmailasync-causes-deadlock-when-throwing-a-specific-exception/28445791#28445791
// SmtpClient causes deadlock when throwing exceptions. This fixes that.
public static class SendMailEx
{
public static Task SendMailExAsync(
this SmtpClient @this,
MailMessage message,
CancellationToken token = default(CancellationToken))
{
// use Task.Run to negate SynchronizationContext
return Task.Run(() => SendMailExImplAsync(@this, message, token));
}
private static async Task SendMailExImplAsync(
SmtpClient client,
MailMessage message,
CancellationToken token)
{
token.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<bool>();
SendCompletedEventHandler handler = null;
Action unsubscribe = () => client.SendCompleted -= handler;
handler = async (_, e) =>
{
unsubscribe();
// a hack to complete the handler asynchronously
await Task.Yield();
if (e.UserState != tcs)
tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
else if (e.Cancelled)
tcs.TrySetCanceled();
else if (e.Error != null)
tcs.TrySetException(e.Error);
else
tcs.TrySetResult(true);
};
client.SendCompleted += handler;
try
{
client.SendAsync(message, tcs);
using (token.Register(() =>
{
client.SendAsyncCancel();
}, useSynchronizationContext: false))
{
await tcs.Task;
}
}
finally
{
unsubscribe();
}
}
}
My code calling the library:
var response = await _fluentEmail
.Subject(emailContents.Subject)
.To(emailContents.To)
.Attach(attachments)
.UsingTemplate(template, emailContents)
.SendAsync(cancellationToken);
The extensions provided by fluent-email did inject these classes as singleton and I did use another lifetime and therefore this issue occured.
So I forgot to also override the dependency injection container configuration for all dependencies using the System.ObjectDisposedException
to use singleton, since I was using a custom implementation of FluentEmail.Smtp.SendMailEx.SendMailExImplAsync
.
After overridding the other dependencies in the DI extension, it worked.