Freigeben über


Using LuisDialog with ConfigurationManager or Environment variables for your keys/secrets

Often when working with developers, they (should) ask how they can use the LuisDialog from the C# BotBuilder SDK without hard coding their subscription key and model id.  I've seen this asked online too in a few places on StackOverflow and Github eg: here and here:  So here's a simple extract which shows how you can pull the keys from ConfigurationManager or the Environment variables in C#

Passing in an instantiated ILuisService into the base class constructor:

 [Serializable]
public class RootDialog : LuisDialog<object>
{
   public RootDialog() : base(new LuisService(new LuisModelAttribute(ConfigurationManager.AppSettings.Get("LuisModelId"), ConfigurationManager.AppSettings.Get("LuisSubscriptionId"))))
   {
   }
   
   [LuisIntent("")]
   [LuisIntent("None")]
   public async Task None(IDialogContext context, IAwaitable<IMessageActivity> message, LuisResult result)
   {
      // Didn't understand the LUIS request
      var msg = await message;
      await context.PostAsync($"I'm not a human");
   }

If you want to use Environment variables, simply change ConfigurationManager.AppSettings with Environment.GetEnvironmentVariable eg:

    public RootDialog() : base(new LuisService(new LuisModelAttribute(Environment.GetEnvironmentVariable("LuisModelId",EnvironmentVariableTarget.Machine), Environment.GetEnvironmentVariable("LuisSubscriptionId", EnvironmentVariableTarget.Machine))))
   {
   }

And ensure your machine environment has those values from the command line using setx eg:

 setx -m LuisModelId your-model-id
setx -m LuisSubscriptionId your-subscription-id

HTH