The following code simulates the problem. I do register the dependency but errors still occur.
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IFoo, Foo>();
var app = builder.Build();
app.MapGet("/", ([FromServices] Foo f) =>
{
f.Print();
return "Hello World!";
});
app.Run();
public interface IFoo
{
void Print();
}
public class Foo : IFoo
{
public void Print()
{
System.Console.WriteLine("Foo's Print()");
}
}
InvalidOperationException: No service for type ‘Foo’ has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
I created the app with dotnet new web -o MyProjectName.
>Solution :
Check the signature of ServiceCollectionServiceExtensions.AddSingleton<TService,TImplementation>(IServiceCollection):
TService– The type of the service to add.
TImplementation– The type of the implementation to use.
You have registered IFoo, not Foo so resolve the interface:
app.MapGet("/", ([FromServices] IFoo f) =>
{
f.Print();
return "Hello World!";
});
P.S.
You should be able to skip the FromServicesAttribute because Minimal API handler support implicit resolution from the DI, i.e. (IFoo f) => ... .