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?
Asked
Active
Viewed 1,966 times
2
-
1Please see the answer here: https://stackoverflow.com/a/31453663/86646 – Eric Dahlvang Jul 25 '18 at 19:29
-
2Possible duplicate of [How to read AppSettings values from Config.json in ASP.NET Core](https://stackoverflow.com/questions/31453495/how-to-read-appsettings-values-from-config-json-in-asp-net-core) – Eric Dahlvang Jul 26 '18 at 19:58
1 Answers
4
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
}
}

Drew Marsh
- 33,111
- 3
- 82
- 100