ASP.Net核心注入设置

Kai*_*i G 3 c# asp.net dependency-injection asp.net-core-1.0

在ASP.Net Core中,可以使用命令将配置值注入到类中IOptions<T>.

所以,如果我有以下appsettings.json配置:

{
  "CustomSection": {
    "Foo": "Bar"
  },
  "RootUrl": "http://localhost:12345/"
}
Run Code Online (Sandbox Code Playgroud)

我可以注入IOptions<CustomSection>我的构造函数(假设我已经定义了一个CustomSection类)并读取Foo属性.

如何将RootUrl设置注入构造函数或不支持?

jky*_*dav 8

创建一个类,如下所示

public class AppSettings {
    public string RootUrl{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

将其注入您的startup.cs,如下所示.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Run Code Online (Sandbox Code Playgroud)

并在控制器中使用它,如下所示.

public CustomerController(IOptions<AppSettings> appSettings)
{
    [variable] = appSettings.Value;
}
Run Code Online (Sandbox Code Playgroud)

如果这对您有用,请告诉我.