Microsoft Dev Blogs

Using Semantic Kernel with Dependency Injection

thumbnail

Table of Contents

  1. Demo App
  2. The Code

Demo App

The code for the application demonstrating usage of dependency injection with Semantic Kernel is found in the library’s GitHub repository. The application, called HomeAutomation, simulates the automation of home devices such as lights. Users need to enter their Azure OpenAI credentials to use the application.

The Code

Setting up Dependency Injection

  1. An application builder is created to set up dependency injection.
  2. Options are loaded into the application.
  3. A singleton IChatCompletionService is created to be re-used by all kernels.
  4. Plugins for the Semantic Kernel are provided.
    • Plugins are provided as singletons to be re-used by multiple kernels.
    • Keyed singletons are used when distinct instances of the same class are needed.
  5. To add an OpenAI or OpenAPI plugin, a temporary kernel is created, the plugin is loaded, and then added as a keyed singleton.
  6. Once all required plugins are registered, a kernel is registered with the desired plugins.

Making Use of Dependency Injection

  1. In Worker.cs, the constructor takes in a Kernel parameter populated by dependency injection.
  2. The selected HomeAutomationKernel keyed Kernel is used with the Worker class.
  3. Services and plugins are typically registered as singletons for re-use/shared between kernels.

By following these steps, Semantic Kernel can be effectively used with dependency injection for efficient and streamlined application development.