Why am I getting the error “Cannot instantiate implementation type” for my generic service?

前端 未结 4 2006
挽巷
挽巷 2021-02-12 09:12

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:



        
相关标签:
4条回答
  • 2021-02-12 09:51

    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.

    0 讨论(0)
  • 2021-02-12 10:07

    Great question and great answers so far, however...

    If your problem is different but the error message is the same

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

    0 讨论(0)
  • 2021-02-12 10:11

    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<>));
    
    0 讨论(0)
  • 2021-02-12 10:12

    This happened to me when service class didn't inherit from IService interface

    0 讨论(0)
提交回复
热议问题