I have a generic repository that I have been instantiating right in my WEB API Controller no problem for a while.
This is what my controller used to look like:
This happened to me recently. I had the implementation class marked "abstract", an artifact of an earlier design. I removed it and the container was able to instantiate the class without a problem.
Great question and great answers so far, however...
...and you are registering the service for a default implementation, without specifying the implementation type, like here:
services.AddScoped<IMyDependency>();
Then the error is unhelpful because it does not give details on why things don't work:
Cannot instantiate implementation type 'MyApp.IMyDependency' for service type 'MyApp.IMyDependency'.
In that case, change the service registration to:
services.AddScoped<IMyDependency, MyDependency>();
That will improve the error message and it will tell you where is the problem, like so:
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MyApp.IMyDependency Lifetime: Transient ImplementationType: MyApp.MyDependency': Unable to resolve service for type 'MyApp.ILowerDependency' while attempting to activate 'MyApp.IMyDependency'.)
In the default ASP.NET core DI container, entire dependency graph needs to be registered explicitly (except maybe for some exceptions like ILogger)
I'm an idiot. I had the Inteface for the implementation. I changed:
services.AddScoped(typeof(IGenericService<>), typeof(IGenericService<>));
to
services.AddScoped(typeof(IGenericService<>), typeof(GenericService<>));
This happened to me when service class didn't inherit from IService interface