-
Notifications
You must be signed in to change notification settings - Fork 200
Resolving scoped service is not supported #198
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
cc @stephentoub. Seems we might want to transfer this to dotnet/extensions? |
What is the problem? Wouldn't this be more about which IServiceProvider is supplied? |
@gong626035906, can you please share a minimal repro of the issue? |
@stephentoub and I had a conversation about this in #201 just after it was merged.
|
It's probably worth mentioning that you could do the following as a workaround for your tool that needs a DbContext. Task<string> GetKnowledge(
IMcpServer thisServer,
IServiceScopeFactory serviceScopeFactory,
[Description("question")] string question)
{
await using scope = serviceScopeFactory.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<CoreDbContext>();
// ...
} This is arguably better than us creating a scope per tool invocation for you, because it gives you explicit control, but I could see us doing it implicitly being handy as well. This would be more in line with HTTP request middleware and SignalR Hub methods which both create a scope per invocation. So, I retract my position on the PR that we shouldn't make any product changes. Using the request services from the /sse streaming request as the tool scope also isn't great, because the scope would last the duration of the session which is probably too long for most scoped services like a DbContext. I'll work on creating a scope per tool invocation. It would still be nice to use the request service scope for stateless tool invocations, since that would be 1:1, but I'll cross that bridge when I get there. |
I recognize the point. Thanks. |
I believe @halter73 is using this issue to track a fix. |
Describe the bug
When I try to inject a service with a Scoped lifetime in the Tool method, an error will occur. I wonder if all injections must be of the Singleton type?
To Reproduce
Steps to reproduce the behavior:
Program.cs
:builder.Services.AddDbContext<CoreDbContext>();
At this point, the lifetime ofCoreDbContext
isScoped
.McpServerTool
method:Expected behavior
Inject CoreDbContext correctly
Logs
The text was updated successfully, but these errors were encountered: