实际上在ASP.NET Core中的ConfigureServices阶段读取AppSettings

问题描述 投票:17回答:2

我需要在ASP.NET Core 1.0 Web应用程序中的ConfigureServices方法中设置一些依赖项(服务)。

问题是,基于新的JSON配置,我需要设置服务或其他服务。

我似乎无法真正阅读应用程序生命周期的ConfigureServices阶段中的设置:

public void ConfigureServices(IServiceCollection services)
{
    var section = Configuration.GetSection("MySettings"); // this does not actually hold the settings
    services.Configure<MySettingsClass>(section); // this is a setup instruction, I can't actually get a MySettingsClass instance with the settings
    // ...
    // set up services
    services.AddSingleton(typeof(ISomething), typeof(ConcreteSomething));
}

我需要实际阅读该部分并决定注册ISomething(可能是与ConcreteSomething不同的类型)。

configuration asp.net-core app-config startup sections
2个回答
25
投票

这就是你可以在appSettings.json方法中从ConfigureServices获取类型化设置的方法:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MySettings>(Configuration.GetSection(nameof(MySettings)));
        services.AddSingleton(Configuration);

        // ...

        var settings = Configuration.GetSection(nameof(MySettings)).Get<MySettings>();
        int maxNumberOfSomething = settings.MaxNumberOfSomething;

        // ...
    }

    // ...
}

9
投票

从ASP.NET Core 2.0开始,我们在构建Program实例时在WebHost类中进行配置设置。此类设置的示例:

return new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .ConfigureAppConfiguration((builderContext, config) =>
    {
        IHostingEnvironment env = builderContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    })

其中,这允许直接在Startup类中使用配置,通过构造函数注入获取IConfiguration的实例(谢谢,内置DI容器):

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    ...
}

0
投票

您可以通过Configuration["ConfigSection:ConfigValue"])访问appsettings.json值

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(o => 
            o.UseSqlServer(Configuration["AppSettings:SqlConn"]));
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System": "Information",
      "Microsoft": "Warning"
    }
  },
  "AppSettings": {
    "SqlConn": "Data Source=MyServer\\MyInstance;Initial Catalog=MyDb;User ID=sa;Password=password;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.