Expand a few DI-related tests (#201)

This commit is contained in:
Stephen Toub 2025-04-03 12:48:23 -04:00 • committed by GitHub
commit a04cf6a2f5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 55 additions and 15 deletions

View file

@ -508,20 +508,33 @@ public class McpServerBuilderExtensionsToolsTests : LoggedTest, IAsyncDisposable
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void WithToolsFromAssembly_Parameters_Satisfiable_From_DI(bool parameterInServices)
[InlineData(ServiceLifetime.Singleton)]
[InlineData(ServiceLifetime.Scoped)]
[InlineData(ServiceLifetime.Transient)]
[InlineData(null)]
public void WithToolsFromAssembly_Parameters_Satisfiable_From_DI(ServiceLifetime? lifetime)
{
ServiceCollection sc = new();
if (parameterInServices)
switch (lifetime)
{
sc.AddSingleton(new ComplexObject());
case ServiceLifetime.Singleton:
sc.AddSingleton(new ComplexObject());
break;
case ServiceLifetime.Scoped:
sc.AddScoped(_ => new ComplexObject());
break;
case ServiceLifetime.Transient:
sc.AddTransient(_ => new ComplexObject());
break;
}
sc.AddMcpServer().WithToolsFromAssembly();
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "EchoComplex");
if (parameterInServices)
if (lifetime is not null)
{
Assert.DoesNotContain("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));
}

View file

@ -45,20 +45,47 @@ public class McpServerToolTests
Assert.Equal("42", result.Content[0].Text);
}
[Fact]
public async Task SupportsServiceFromDI()
[Theory]
[InlineData(ServiceLifetime.Singleton)]
[InlineData(ServiceLifetime.Scoped)]
[InlineData(ServiceLifetime.Transient)]
public async Task SupportsServiceFromDI(ServiceLifetime injectedArgumentLifetime)
{
MyService expectedMyService = new();
MyService singletonService = new();
ServiceCollection sc = new();
sc.AddSingleton(expectedMyService);
switch (injectedArgumentLifetime)
{
case ServiceLifetime.Singleton:
sc.AddSingleton(singletonService);
break;
case ServiceLifetime.Scoped:
sc.AddScoped(_ => new MyService());
break;
case ServiceLifetime.Transient:
sc.AddTransient(_ => new MyService());
break;
}
sc.AddSingleton(services =>
{
return McpServerTool.Create((MyService actualMyService) =>
{
Assert.NotNull(actualMyService);
if (injectedArgumentLifetime == ServiceLifetime.Singleton)
{
Assert.Same(singletonService, actualMyService);
}
return "42";
}, new() { Services = services });
});
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = McpServerTool.Create((MyService actualMyService) =>
{
Assert.Same(expectedMyService, actualMyService);
return "42";
}, new() { Services = services });
McpServerTool tool = services.GetRequiredService<McpServerTool>();
Assert.DoesNotContain("actualMyService", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema));