c# - .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();
}
}
解决方案
推荐阅读
- python - 运行 script.exe 给出 PermissionError: [Errno 13] ,但在 script.py 中运行相同的代码不会
- node.js - 如何在 Node.js 中过滤这个对象数组?
- sql - 如何更新由标准 SQL 中的查询创建的表?
- redux - 是否可以在 createAsyncthunk 中手动调度 thunk 状态
- javascript - React js 导入大数据文件(json)
- reactjs - Gatsby build,failed Building production JavaScript and CSS bundles error
- listview - 如何创建一次只显示一个元素的水平列表?
- spring - 离线环境下无法使用 gradle bootBuildImage 构建镜像
- android - Qmetry 错误:基础驱动程序是 QAFExtendedWebDriver。此步骤需要 AndroidDriver
- python - 为什么python可执行文件的图标从'dist文件夹中消失了?