如何从 Startup.cs 中 InjectsAuthElements 方法的配置中获取连接字符串

How can I get the connection string from configuration in the InjectsAuthElements methods in Startup.cs

我正在尝试使用 sql 服务器 配置 elmah。 我看到的配置是这样的

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    }
    private static void InjectsAuthElements(IServiceCollection services)
    {
        ...
        services.AddElmah<SqlErrorLog>(options =>
        {
            options.Path = "ElmahNewNameForSecurity.axd";
            options.OnPermissionCheck = context => context.User.Identity.IsAuthenticated && context.User.IsInRole("Admin");
            options.ConnectionString = "MyConnectionString";
        });
    }
}

我想用 Configuration.GetConnectionString("Default").

之类的东西替换 MyConnectionString

要获取连接字符串,可以使用IConfiguration

public class Startup
{
  private readonly IConfiguration _configuration;
  public Startup(IConfiguration configuration)
  {
        _configuration = configuration; 
  }

  public void ConfigureServices(IServiceCollection services)
  {
    ...
  }

  private static void InjectsAuthElements(IServiceCollection services)
  {
    ...
    services.AddElmah<SqlErrorLog>(options =>
    {
        options.Path = "ElmahNewNameForSecurity.axd";
        options.OnPermissionCheck = context => 
        context.User.Identity.IsAuthenticated && 
        context.User.IsInRole("Admin");
        options.ConnectionString = 
               _configuration.GetConnectionString("MyConnectionString");
        });
     }
   }
}

只需添加一个IConfiguration接口作为方法的第二个参数,并在调用方法时传递Configuration

private static void InjectsAuthElements(
    IServiceCollection services,
    IConfiguration configuration)
{
    ...
    services.AddElmah<SqlErrorLog>(options =>
    {
        options.Path = "ElmahNewNameForSecurity.axd";
        options.OnPermissionCheck = context => context.User.Identity.IsAuthenticated && context.User.IsInRole("Admin");
        options.ConnectionString = "MyConnectionString";
    });
}