Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core No service for type has been registered

I have the following two classes

public class RepositoryConnection : IRepositoryConnection{

    public RepositoryConnection(IConfiguration configuration, ILogger<RepositoryConnection> logger){
    //STUFF
    }

}

public class AuthenticationTokenFactory : IAuthenticationTokenFactory {

   public AuthenticationTokenFactory(ILogger<AuthenticationTokenFactory> logger) {
    //STUFF 
    }
}

Here is my Startup.cs

public class Startup {

    public Startup(IConfiguration configuration) {
        Configuration = configuration;
    }
    public void ConfigureServices(IServiceCollection services) {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddSingleton<IAuthenticationTokenFactory, AuthenticationTokenFactory>();
        services.AddSingleton<IRepositoryConnection,RepositoryConnection>();
   }
}

I can successfully inject IAuthenticationTokenFactory to controllers but when i try to inject IRepositoryConnection i get the following error→

InvalidOperationException: No service for type 'TrainingCommerce.Accessors.RepositoryConnection' has been registered.


Thanks to comments i immediately noticed my wrongful ways. I was trying to access at another line

var debug = ControllerContext.HttpContext.RequestServices.GetRequiredService<RepositoryConnection>();
like image 832
Hasan Emrah Süngü Avatar asked Mar 05 '23 14:03

Hasan Emrah Süngü


1 Answers

Try injecting the interface instead of the implementation:

In your sample you inject ILogger<RepositoryConnection> logger this is a typo and should be: ILogger<IRepositoryConnection> logger.

So:

public class RepositoryConnection : IRepositoryConnection{
    public RepositoryConnection(IConfiguration configuration, ILogger<IRepositoryConnection> logger){
    //STUFF
    }
}
like image 109
Mike Bovenlander Avatar answered Mar 15 '23 18:03

Mike Bovenlander