SMTP 客户端作为 Azure Functions 应用中的单例

STMP Client as Singleton in Azure Functions app

我有一个 Azure Functions 应用程序,它使用 Amazon SES 服务发送电子邮件并处理发送消息操作,我创建了一个客户端并在我的 Azure 应用程序的 Startup.cs 中将其声明为单例。

看起来第一条消息发送正常,但后续消息发送失败并出现以下错误:

Cannot access a disposed object. Object name: 'System.Net.Mail.SmtpClient'

这是我处理发送消息的客户端的样子:

using System;
using System.Net;
using System.Net.Mail;

public class SesClient
{

    SmtpClient _client;
    private string _senderEmail;

    public SesClient(string smtpServer, int smtpPort, string amazonSesUserId, string amazonSesPassword, string senderEmail)
    {
        if (_client == null)
        {
            _client = new SmtpClient(smtpServer, smtpPort);
            _client.Credentials = new NetworkCredential(amazonSesUserId, amazonSesPassword);
            _client.EnableSsl = true;
            _senderEmail = senderEmail;
        }
    }

    public void SendEmailMessage(MailMessage message)
    {
        message.From = new MailAddress(_senderEmail, "John Doe");

        using (_client)
        {
            try
            {
                _client.Send(message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

然后我在 Startup.csConfigureServices() 方法中将此 class 创建为单例,如下所示:

var smtpServer = Configuration["AmazonSes:SMTP_SERVER"];
var smtpPort = Convert.ToInt32(Configuration["AmazonSes:SMTP_PORT"]);
var sesUserId = Configuration["AmazonSes:USER_ID"];
var sesPassword = Configuration["AmazonSes:USER_PASSWORD"];
var senderEmail = Configuration["MyApp:EMAIL_ADDRESS"];

services.AddSingleton(new SesClient(smtpServer, smtpPort, sesUserId, sesPassword, senderEmail));

我认为将此客户端创建为单例是正确的想法。那是问题所在吗?如果不是,知道这里可能是什么问题吗?

在您发布的代码中,using(_client) 在发送第一封电子邮件后有效地处理了 SmtpClient,因此出现了“对象处理”异常。由于它是单例,因此不会再次调用构造函数。