Provide multiple SendCompleted callbacks to SmtpClient
https://softwareengineering.stackexchange.com/questions/202499
-
29-09-2020 - |
Question
I have an Email
class that has a Send
method that optionally takes an SmtpClient
and sends an email asynchronously using SendAsync
. If no SmtpClient
is supplied to this method, it instantiates a default SmtpClient
and uses that to send the email. Inside the Send
function, I provide a SendCompleted
callback which disposes of the MailMessage
and the default SmtpClient
if one was not supplied to the method.
So when I am supplying the SmtpClient
, how do I go about disposing it?
I can't dispose of it inside Send
because it may be used for sending other emails, plus I figure it's the responsibility of the thing that instantiated the passed in SmtpClient
to dispose of it again. Is it possible to add multiple SendCompleted
callbacks to the SmtpClient
that run after each other?
Solution
There are two major ways of going about destroying your SmtpClient
objects.
- The
SmtpClient
manages its own lifetime (i.e. destroys itself when the time comes). This is easiest if eachSmtpClient
is used for only one email, but it can be made to work for multiple, ifSmtpClient
knows how many emails it sent and it can be guaranteed that theSendCompleted
callback is invoked a corresponding number of times. - An outside component manages the lifetime of
SmtpClient
(this can be the object that createdSmtpClient
or some other object). In this case, theSmtpClient
needs to inform the object responsible for managing its lifetime about theSendCompleted
callback being invoked. This is usually done by invoking a callback on that object from withinSendCompleted
.