首页 > 解决方案 > .Net 核心依赖注入,这是每个请求的 SmtpClient 的新实例吗?

问题描述

我们正在注入一个接受SmtpClient作为参数的自定义邮件程序,这取决于我们是否正在调试,我们使用稍微不同的实现SmtpClient

public static void AddSmtpMailer(this IServiceCollection services, IHostingEnvironment environment)
{
    services.AddTransient<IMailer<BaseModel>>(x => new Mailer<BaseModel>(
        environment.IsDevelopment()
            ? new SmtpClient
            {
                PickupDirectoryLocation = @"c:\temp",
                DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
            }
        : new SmtpClient
        {
            Host = "mail.someplace.com",
            Port = 25,
            EnableSsl = true,
            Credentials = new NetworkCredential("user", "password")
        },
        environment.ContentRootPath, environment.IsLive()));
}

但是,我们发现当我们尝试快速连续发送多封电子邮件时,我们会收到以下错误: 错误信息

SmtpClient因此,我的问题是:我们是否每次都会获得一个新实例?因为这似乎是与发送多封相同SmtpClient. 我们是否在启动时创建单个实例SmtpClient并每次重用它?

请注意,我们也尝试过.AddScoped但发现了相同的行为。

使用 SmtpClient 的实际代码是:

 public sealed class Mailer<T> :IDisposable, IMailer<T> where T : BaseModel
{
    private readonly SmtpClient _smtpClient;
    private readonly string _contentRootPath;
    private readonly bool _forceSandbox;

    public Mailer(SmtpClient smtpClient, string contentRootPath, bool isLive)
    {
        _smtpClient = smtpClient;
        _contentRootPath = contentRootPath;
        _forceSandbox = !isLive;
    }

    public async Task<bool> SendEmail(T model, string template)
    {
        if (template.Contains(".cshtml"))
            template = template.Replace(".cshtml", "");

        Email.DefaultSender = new SmtpSender(_smtpClient);
        Email.DefaultRenderer = new RazorRenderer();

        var email = Email
            .From(model.From.Email, model.From.Name.NullOrEmptyTo(model.From.Email))
            .To(EmailAddressHelper.GetAddressesFromModel(model.Recipients, _forceSandbox))
            .Subject(model.Subject)
            .UsingTemplateFromFile($@"{_contentRootPath}\views\{template}.cshtml", model)
            .Attach(EmailAttachmentHelper.GetAttachmentsFromModel(model.Attachments));

        if (model.CcRecipients != null && model.CcRecipients.Any())
            email.CC(EmailAddressHelper.GetAddressesFromModel(model.CcRecipients, _forceSandbox));

        if (model.BccRecipients != null && model.BccRecipients.Any())
            email.BCC(EmailAddressHelper.GetAddressesFromModel(model.BccRecipients, _forceSandbox));

        email.Data.Headers = EmailHeaderHelper.GetHeaders(model.UniqueID, model.Headers);

        var result = await email.SendAsync();
        return result.Successful;
    }

    public void Dispose()
    {
        _smtpClient?.Dispose();
    }
}

标签: c#asp.net-coredependency-injectionsmtpclient

解决方案


推荐阅读