A version of this answer by Teoman shipahi that correctly disposes of the SmtpClient
.
First make ISmtpClient
inherit IDisposable
:
public interface ISmtpClient : IDisposable
{
void Send(MailMessage mailMessage);
}
Then implement IDisposable
in the SmtpClientWrapper
class:
public class SmtpClientWrapper : ISmtpClient
{
private bool disposed;
private readonly SmtpClient smtpClient;
public SmtpClientWrapper(string host, int port)
{
smtpClient = new SmtpClient(host, port);
}
~SmtpClientWrapper()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
smtpClient?.Dispose();
}
disposed = true;
}
}
protected void CheckDisposed()
{
if (disposed)
{
throw new ObjectDisposedException(nameof(SmtpClientWrapper));
}
}
public void Send(MailMessage mailMessage)
{
CheckDisposed();
smtpClient.Send(mailMessage);
}
}
For this version of SmtpClientWrapper
, I have removed the SmtpClient
property to avoid the problem of the SmtpClient
objects not being disposed of when replaced in setter of the SmtpClient
property.