botframework v4,访问appsettings.json

时间:2018-07-25 17:48:29

标签: botframework appsettings

如何在botframework(v4)应用程序中读取appsettings.json文件?我看到该配置是在Startup.cs中设置的,但是如何访问其他类中的设置?

1 个答案:

答案 0 :(得分:1)

v4 ASP.NET Core集成的目标之一是使现有.NET Core模式习惯。这意味着的一件事是,当实现IBot并将其与AddBot<TBot>相加时,它就像ASP.NET MVC控制器一样成为依赖项注入的参与者。这意味着您可能需要访问的任何服务(包括配置类型(例如IOptions<T>)都可以通过构造函数注入到您的bot中,如果您需要的话。

在这种情况下,您只想利用Configuration API中的the "options pattern",看起来像这样:

Startup.cs

public class Startup
{
  private readonly IConfiguration _configuration;

  public Startup(IConfiguration configuration)
  {
    _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
  }

  public void ConfigureServices(IServiceCollection services)
  {
    // Bind MySettings to a section named "mySettings" from config
    services.Configure<MySettings>(_configuration.GetSection("mySettings"));

    // Add the bot
    services.AddBot<MyBot>();
  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    app.UseBotFramework();
  }
}

MyBot.cs

public class MyBot : IBot
{
  private readonly IOptions<MySettings> _mySettings;

  public MyBot(IOptions<MySettings> mySettings)
  {
    _mySettings = mySettings ?? throw new ArgumentNullException(nameof(mySettings));
  }

  public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
  {
     // use _mySettings here however you like here
  }
}