Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error still occurs even after registering the required dependency, what is wrong?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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) => ... .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading