Bercovici Adrian
Bercovici Adrian

Reputation: 9380

Unable to resolve base class service

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?

Upvotes: 3

Views: 522

Answers (1)

Steven
Steven

Reputation: 172835

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

Upvotes: 4

Related Questions