Brian Moore
Brian Moore

Reputation: 41

botframework v4, accessing appsettings.json

How do I read the appsettings.json file in my botframework (v4) app? I see the configuration is set up in the Startup.cs, but how do I access the settings in other classes?

Upvotes: 2

Views: 2134

Answers (1)

Drew Marsh
Drew Marsh

Reputation: 33379

One of the goals of the v4 ASP.NET core integration was to be idiomatic to existing .NET Core patterns. One of the things this means is that when you implement an IBot and add it with AddBot<TBot>, it becomes a participant in dependency injection just like an ASP.NET MVC controller would. This means that any services you might need to access, including configuration types such as IOptions<T>, will be injected into your bot via the constructor if you ask for them.

In this case, you just want to leverage the "options pattern" from the Configuration APIs and that would look something like this:

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
  }
}

Upvotes: 4

Related Questions