C# 收到异常时在Startup.cs文件中使用Configure()中的IEmailSender
当我收到异常时,我想在Startup.cs文件中的Configure方法中发送一封电子邮件 在应用程序的其余部分,我正在使用并在Startup.cs文件中注册它,就像这样C# 收到异常时在Startup.cs文件中使用Configure()中的IEmailSender,c#,asp.net-core,C#,Asp.net Core,当我收到异常时,我想在Startup.cs文件中的Configure方法中发送一封电子邮件 在应用程序的其余部分,我正在使用并在Startup.cs文件中注册它,就像这样 public void ConfigureServices(IServiceCollection services) { services.AddTransient<IEmailSender, EmailSender>(); } 从上下文中提取服务提供者,并使用它来解析所需的类型 public void
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IEmailSender, EmailSender>();
}
从上下文中提取服务提供者,并使用它来解析所需的类型
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder) {
//...
app.UseExceptionHandler(errorApp => {
errorApp.Run(async context => {
IServiceProvider services = context.RequestServices;
IEmailSender emailSender = services.GetRequiredService<IEmailSender>();
UserExceptionOptions options = services.GetRequiredService<IOptions<UserExceptionOptions>>().Value;
await emailSender.SendEmailAsync(options.ExceptionEmailAddress, "some subject", "hey an exception error!");
});
});
//...
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、种子播种机){
//...
app.UseExceptionHandler(errorApp=>{
errorApp.Run(异步上下文=>{
IServiceProvider服务=context.RequestServices;
IEmailSender=services.GetRequiredService();
UserExceptionOptions=services.GetRequiredService().Value;
等待emailSender.SendEmailAsync(options.ExceptionEmailAddress,“某些主题”,“嘿,异常错误!”);
});
});
//...
}
然后,可以根据需要使用已解析的服务
public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder) {
//...
app.UseExceptionHandler(errorApp => {
errorApp.Run(async context => {
IServiceProvider services = context.RequestServices;
IEmailSender emailSender = services.GetRequiredService<IEmailSender>();
UserExceptionOptions options = services.GetRequiredService<IOptions<UserExceptionOptions>>().Value;
await emailSender.SendEmailAsync(options.ExceptionEmailAddress, "some subject", "hey an exception error!");
});
});
//...
}