Dependency injection with native function didn't work! #7170
-
I have a plugin with dependency of another class (For file handling). This is my code: var builder = WebApplication.CreateBuilder(args);
var env = builder.Environment.EnvironmentName;
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.AddCommandLine(args)
.Build();
Console.WriteLine(env);
// Add services to the container.
builder.Services.AddRazorPages();
// Azure OpenAI
var AzureOpenAIConfig = config.GetRequiredSection("AzureOpenAI").Get<AzureOpenAIConfig>();
Console.WriteLine(AzureOpenAIConfig.DeploymentName);
builder.Services.AddAzureOpenAIChatCompletion(
deploymentName: AzureOpenAIConfig.DeploymentName,
endpoint: AzureOpenAIConfig.EndPoint,
apiKey: AzureOpenAIConfig.ApiKey
);
builder.Services.AddTransient<IFileManager, FileManager>();
// Create native plugin collection
builder.Services.AddTransient((serviceProvider) =>
{
KernelPluginCollection pluginCollection = [];
pluginCollection.AddFromType<MyPlugin>("MyPlugin");
return pluginCollection;
});
// Create the kernel service
builder.Services.AddTransient<Kernel>((serviceProvider) =>
{
KernelPluginCollection pluginCollection = serviceProvider.GetRequiredService<KernelPluginCollection>();
return new Kernel(serviceProvider, pluginCollection);
});
var app = builder.Build();
public class MyPlugin
{
private readonly IFileManager _fileManager;
public ExcelPlugin(IFileManager fileManager)
{
this._fileManager = fileManager;
if (fileManager == null)
{
Console.WriteLine("FileManager is NULL!!!");
}
}
}
I can inject the IFileManager in other classes, but not in my plugin. Exception: |
Beta Was this translation helpful? Give feedback.
Answered by
imranshams
Jul 11, 2024
Replies: 1 comment
-
I found a very dirty solution, it is just working. So I changed the plugin as below: public class MyPlugin
{
private readonly IFileManager _fileManager;
public ExcelPlugin(IServiceProvider serviceProvider)
{
_fileManager = serviceProvider.GetService<IFileManager>()!;
}
} And finally the way which I create the Native Plugin: // Create native plugin collection
builder.Services.AddTransient((serviceProvider) =>
{
KernelPluginCollection pluginCollection = [];
pluginCollection.AddFromObject<MyPlugin>(new MyPlugin(serviceProvider),"MyPlugin");
return pluginCollection;
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
sophialagerkranspandey
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found a very dirty solution, it is just working.
So I changed the plugin as below:
And finally the way which I create the Native Plugin: