【问题标题】:Using my IEmailSender from Configure() in my Startup.cs file when I receive exceptions当我收到异常时,在 Startup.cs 文件中使用 Configure() 中的 IEmailSender
【发布时间】:2019-10-03 23:20:57
【问题描述】:

当我收到异常时,我想在 Startup.cs 文件中的 Configure 方法中发送一封电子邮件。

我正在使用 IEmailSender 并将其注册到 Startup.cs 文件中,就像应用程序的其余部分一样。

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IEmailSender, EmailSender>();
}

但是现在我想在收到异常时在 Configure 方法中使用它,但我不确定如何实例化它和/或使用 _emailSender,它是一个 IEmailSender,通常被注入到使用它的类,但在这种情况下(Startup.cs)我无法注入它,因为直到 ConfigureServices 方法运行并将其添加为服务之前它尚未定义。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seed seeder)
{
     app.UseExceptionHandler(builder => { builder.Run(async context => {
     // where _emailSender is a IEmailSender emailSender   
     await _emailSender.SendEmailAsync("someone@gmail.com", "some subject", "hey an exception error!");
       });
     });
}

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    从上下文中提取服务提供者并使用它来解析所需的类型

    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!");
            });
        });
    
        //...
    }
    

    然后可以根据需要使用已解析的服务

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 2015-10-11
      • 2015-02-18
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2013-10-21
      相关资源
      最近更新 更多