c# - ASP.Net Core 注入(inject)设置

标签 c# asp.net dependency-injection asp.net-core-1.0

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

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

{
  "CustomSection": {
    "Foo": "Bar"
  },
  "RootUrl": "http://localhost:12345/"
}

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

如何注入(inject) RootUrl设置到我的构造函数中还是不支持?

最佳答案

创建一个类如下

public class AppSettings {
    public string RootUrl{ get; set; }
}

如下所示将其注入(inject)您的 startup.cs。

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}

并在您的 Controller 中使用它,如下所示。

public CustomerController(IOptions<AppSettings> appSettings)
{
    [variable] = appSettings.Value;
}

让我知道这是否适合您。

关于c# - ASP.Net Core 注入(inject)设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40478175/

相关文章:

c# - Visual Studio 2010 EXE 打包

asp.net - 在 PDF iText ASP C# 中为我的所有页面设置修复背景图像

css - 如何在 GridView 单元格内设置链接颜色

asp.net - 扩展ASP.NET验证器

java - 如何从现场注入(inject)?

c# - 统一: No parameterless constructor defined for this object.

Angular 2 依赖注入(inject)不起作用

c# - 如何防止在多个选项卡中共享用户定义的 session ?

c# - 移除对 IoC 容器的依赖

c# - 您如何识别授予使用 Microsoft Graph 和 C# 的应用程序的所有权限?