3

When trying to activate a Controller I get the following error due to a service not properly injected:

System.InvalidOperationException: 'Unable to resolve service for type 'AnubisServer.Server.IDroneOperations' while attempting to activate 'AnubisServer.DroneController'.'

I have the following hierachy:

public interface IOperations { } public interface ICatalog : IOperations { } public interface IAdmin : ICatalog { } public interface ICatalogService : IAdmin, ISomethingElse { } 

In my startup i am providing a concrete implementation for the most derived interface ICatalogService:

Startup

public void ConfigureServices(IServiceCollection services) { services.AddMvc(); ICatalogService catalogService = new SomeConcreteService(); services.AddSingleton(catalogService); } 

Controller

public class CatalogController:Controller { private IOperations operations; public CatalogController(IOperations ops) { this.operations=ops; } } 

So I do not understand why it does not work to inject a base class interface since i am providing a derived concrete instance.

Any ideas?

1
  • 1
    Try services.AddSingleton<IOperations>(catalogService) Commented May 22, 2019 at 9:29

1 Answer 1

4

Registrations in IServiceCollection are key-value pairs, where the service (or abstraction) is the key and the component (or implementation) is the value. Lookup will be done based on that exact key. So in your case you only registered ICatalogService, and not IOperations. This means the IOperations can't be resolved. You will have to register IOperations explicitly. For instance:

services.AddSingleton<IOperations>(catalogService); 
Sign up to request clarification or add additional context in comments.

2 Comments

Well, most framework do provide something like AsImplementedInterfaces() (in AutoFac) hence will resolve correctly for the case in question.
@haim770: You are right about this, but I think the core problem here is OP's understanding of how DI Containers work (with a basic key-value pair dictionary lookup).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.