Scenario
Around 20 ASP.net(VB) applications share the same code framework and when deployed also shares a common web.config. Throughout the various applications we use System.Net.Mail.SmtpClient/MailMessage to send e-mails and now we would like to implement an e-mail opt-out feature for our users with a minimal amount of change to the existing code. That leaves out the simplest approach; inheriting a class from SmtpClient, say OurSmtpClient, and override the Send() method to remove all users that have opted to not receive e-mails, as that would mean we would have to change all New SmtpClient() to New OurSmtpClient() throughout the apps.
Alternatives
We’ve previously used tagMapping to remap tags to our in-house, derived alternatives, are there anything similar for classes so that all SmtpClient automatically becomes OurSmtpClient and thus will use the overridden Send() method?
We’ve also looked at Extensions, but the problem here is that we can’t override existing methods, only add new ones?
Next alternative we have considered is reflection, but we couldn’t get our minds around on how to actually implement it.
Events .. Oh, if there was a Sending event …
Code (cause everyone likes it)
Here is the inherit approach, just to understand what we are looking for:
Public Class OurSmtpClient
Inherits SmtpClient
Public Overloads Sub Send(message As MailMessage)
For i As Integer = message.To.Count - 1 To 0 Step -1
With message.To(i)
If (.Address.Contains("test")) Then
message.To.RemoveAt(i)
End If
End With
Next
MyBase.Send(message)
End Sub
End Class
Any suggestions? How can this be done without changing the code in the existing applications and only in the shared code (lives in App_Code in the apps) or the shared web.config?
The fact that you are struggling to implement what should be a straightforward requirement is a big clue that you’ve built up too much technical debt. Your post conveys a strong reluctance to pay down technical debt. This is something that you must avoid and instead embrace Merciless Refactoring. Bite the bullet and introduce that specialised SMTP class.