Search code examples
c#dependency-injectionasp.net-coreasp.net-core-mvc

Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered


I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:

InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.

Repository:

public interface IBloggerRepository { ... }

public class BloggerRepository : IBloggerRepository { ... }

Controller:

public class BlogController : Controller
{
    private readonly IBloggerRepository _repository;

    public BlogController(BloggerRepository repository)
    {
        _repository = repository;
    }

    public IActionResult Index() { ... }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    
    services.AddScoped<IBloggerRepository, BloggerRepository>();
}

I'm not sure what I'm doing wrong. Any ideas?


Solution

  • To break down the error message:

    Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.

    That is saying that your application is trying to create an instance of BlogController but it doesn't know how to create an instance of BloggerRepository to pass into the constructor.

    Now look at your startup:

    services.AddScoped<IBloggerRepository, BloggerRepository>();
    

    That is saying whenever a IBloggerRepository is required, create a BloggerRepository and pass that in.

    However, your controller class is asking for the concrete class BloggerRepository and the dependency injection container doesn't know what to do when asked for that directly.

    I'm guessing you just made a typo, but a fairly common one. So the simple fix is to change your controller to accept something that the DI container does know how to process, in this case, the interface:

    public BlogController(IBloggerRepository repository)
    //                    ^
    //                    Add this!
    {
        _repository = repository;
    }
    

    Note that some objects have their own custom ways to be registered, this is more common when you use external Nuget packages, so it pays to read the documentation for them. For example if you got a message saying:

    Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' ...

    Then you would fix that using the custom extension method provided by that library which would be:

    services.AddHttpContextAccessor();
    

    For other packages - always read the docs.