ASP.NET Core 注入和获取 AppSettings 配置

ASP.NET Core 项目中有个appsettings.json配置文件,用于存放一些配置信息,比如数据库连接字符串等,但访问的话,只能在 ASP.NET Core 项目中获取,如果我们在其他项目类库中,该怎样获取呢?

实现方式就是利用 ASP.NET Core DI,将配置信息注入到 IoC 中,通过构造函数获取注入的对象。

appsettings.json示例代码:

{
  "AppSettings": {
    "AccessKey": "111111",
    "SecretKey": "22222",
    "Bucket": "3333333",
    "Domain": "http://wwww.domain.com"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Error",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

对应AppSettings对象代码:

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

    public string SecretKey { get; set; }

    public string Bucket { get; set; }

    public string Domain { get; set; }
}

ConfigureServices添加配置代码:

public void ConfigureServices(IServiceCollection services)
{
    var appSettings = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettings);
    services.AddTransient<IUpoladService, UpoladService>();

    // Add framework services.
    services.AddMvc();
}

UpoladService通过构造函数方式获取注入对象:

public class UpoladService : IUpoladService
{
    private AppSettings _appSettings;

    public UpoladService(IOptionsMonitor<AppSettings> appSettings)
    {
        _appSettings = appSettings.CurrentValue; //IOptions 需要每次重新启动项目加载配置,IOptionsMonitor 每次更改配置都会重新加载,不需要重新启动项目。
    }
}

参考资料:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值