InvalidOperationException: Unable to resolve service for type

By FoxLearn 2/4/2025 9:00:56 AM   318
When the built-in dependency injection framework attempts to create an object, it needs to resolve all constructor parameters.

If it fails to resolve one of them, it will throw an exception, such as:

  • InvalidOperationException: Unable to resolve service for type <Type Name> while attempting to activate <Type Name>.
  • ArgumentException: Cannot instantiate implementation type <Type Name> for service type <Type Name>.

The type of exception depends on how you are registering the services.

First, I'll provide a solution, then explore different ways the issue can occur.

The easiest way to resolve this issue is to explicitly register the type and, if necessary, specify how to construct it, particularly for constructor parameters that are primitive types.

For example, Imagine you have a class ApiService with the following constructor:

public ApiService(string endpointUrl)

To register this service correctly, you would need to explicitly tell the DI container how to create it:

// Registering the ApiService with a primitive parameter
builder.Services.AddSingleton<IApiService>(_ => new ApiService("https://api.example.com"));

If you have more than one primitive parameter, it's better to encapsulate them in a dedicated configuration class.

For example, if your ApiService needs a string (for the endpoint) and an int (for the timeout):

public class ApiConfig
{
    public string EndpointUrl { get; set; }
    public int Timeout { get; set; }
}

Then modify the ApiService constructor:

public ApiService(ApiConfig config, IClient client)

Now, register everything in the container:

builder.Services.AddSingleton<IClient, HttpClient>();
builder.Services.AddSingleton<ApiConfig>(_ => new ApiConfig
{
    EndpointUrl = "https://api.example.com",
    Timeout = 30
});

builder.Services.AddSingleton<IApiService, ApiService>();

Example Causes and Solutions

Cause 1services.AddSingleton<IApiService, ApiService>()

If you attempt to register ApiService and the constructor takes a primitive parameter, like this:

builder.Services.AddSingleton<IApiService, ApiService>();

You’ll get an exception like:

InvalidOperationException: Unable to resolve service for type ‘System.String’ while attempting to activate ‘ApiService’.

This happens because the DI container doesn’t know how to resolve the string parameter. The solution is to tell it explicitly how to instantiate the ApiService, as shown in the earlier solution.

Cause 2services.AddSingleton<IApiService>()

When you try to register ApiService without specifying how to instantiate it, like this:

builder.Services.AddSingleton<IApiService>();

You’ll encounter an exception like:

ArgumentException: Cannot instantiate implementation type ‘IApiService’ for service type ‘IApiService’.

The DI container doesn't know which concrete type to use to resolve IApiService.

Cause 3 - Missing Registration for Dependent Services

Let’s say you have a controller that depends on IApiService:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IApiService _apiService;

    public WeatherForecastController(IApiService apiService)
    {
        _apiService = apiService;
    }
    
    // Other actions
}

If you don’t register IApiService before attempting to activate WeatherForecastController, you’ll encounter:

InvalidOperationException: Unable to resolve service for type ‘IApiService’ while attempting to activate ‘Controllers.WeatherForecastController’.

This happens because the container has no idea how to resolve IApiService.

To avoid these exceptions, always ensure that your services are properly registered with the DI container, particularly if they have constructor parameters that need specific values or types.