diff --git a/src/Flandre.Framework/Flandre.Framework.csproj b/src/Flandre.Framework/Flandre.Framework.csproj index 5f74a10..3c0601f 100644 --- a/src/Flandre.Framework/Flandre.Framework.csproj +++ b/src/Flandre.Framework/Flandre.Framework.csproj @@ -2,7 +2,7 @@ Flandre.Framework - 1.0.0-rc.5 + 1.0.0-rc.6 FlandreDevs 现代化、跨平台的聊天机器人框架,一次编写,多处运行。 bot;chatbot;flandre;framework diff --git a/src/Flandre.Framework/FlandreApp.cs b/src/Flandre.Framework/FlandreApp.cs index dcd2347..cfde77f 100644 --- a/src/Flandre.Framework/FlandreApp.cs +++ b/src/Flandre.Framework/FlandreApp.cs @@ -88,7 +88,8 @@ void WithCatch(Type pluginType, Func subscriber, string? eventName { try { - var plugin = (Plugin)Services.GetRequiredService(pluginType); + using var scope = Services.CreateScope(); + var plugin = (Plugin)scope.ServiceProvider.GetRequiredService(pluginType); await subscriber.Invoke(plugin); } catch (Exception e) @@ -146,8 +147,9 @@ private void LoadPlugins() { foreach (var pluginType in _pluginTypes) { - var loadCtx = new PluginLoadContext(pluginType, Services); - var plugin = (Plugin)Services.GetRequiredService(pluginType); + using var scope = Services.CreateScope(); + var loadCtx = new PluginLoadContext(pluginType, scope.ServiceProvider); + var plugin = (Plugin)scope.ServiceProvider.GetRequiredService(pluginType); loadCtx.LoadFromAttributes(); // Fluent API can override attributes diff --git a/src/Flandre.Framework/InternalMiddlewares.cs b/src/Flandre.Framework/InternalMiddlewares.cs index 0d74309..627edfd 100644 --- a/src/Flandre.Framework/InternalMiddlewares.cs +++ b/src/Flandre.Framework/InternalMiddlewares.cs @@ -30,7 +30,12 @@ private FlandreApp UsePluginMessageHandler() UseMiddleware(async (ctx, next) => { - _pluginTypes.ForEach(p => ((Plugin)Services.GetRequiredService(p)).OnMessageReceivedAsync(ctx)); + _pluginTypes.ForEach(p => + { + // create a new scope instead of using ctx scope + using var scope = Services.CreateScope(); + ((Plugin)scope.ServiceProvider.GetRequiredService(p)).OnMessageReceivedAsync(ctx); + }); await next(); }); return this; @@ -212,6 +217,7 @@ public FlandreApp UseCommandInvoker() if (!ctx.Command.TryParse(ctx.CommandStringParser, cmdService, out var result)) return result.ErrorText!; + // ctx.Service is a service scope var plugin = (Plugin)ctx.Services.GetRequiredService(ctx.Command.PluginType); var pluginLogger = (ILogger)Services.GetRequiredService(plugin.LoggerType);