Using Semantic Kernel with Dependency Injection

Table of Contents
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
- An application builder is created to set up dependency injection.
- Options are loaded into the application.
- A singleton
IChatCompletionService
is created to be re-used by all kernels. - 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.
- To add an OpenAI or OpenAPI plugin, a temporary kernel is created, the plugin is loaded, and then added as a keyed singleton.
- Once all required plugins are registered, a kernel is registered with the desired plugins.
Making Use of Dependency Injection
- In
Worker.cs
, the constructor takes in aKernel
parameter populated by dependency injection. - The selected
HomeAutomationKernel
keyed Kernel is used with theWorker
class. - 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.