Search code examples
c#asp.net-coredependency-injectionasp.net-core-mvc

Unable to resolve service for type while attempting to activate


In my ASP.NET Core application, I get the following error:

InvalidOperationException: Unable to resolve service for type 'Cities.Models.IRepository' while attempting to activate 'Cities.Controllers.HomeController'.

I the HomeController I am trying to pass the Cities getter to the view like so:

public class HomeController : Controller
{
    private readonly IRepository repository;

    public HomeController(IRepository repo) => repository = repo;

    public IActionResult Index() => View(repository.Cities);
}

I have one file Repository.cs that contains an interface and its implementation like so:

public interface IRepository
{
    IEnumerable<City> Cities { get; }
    void AddCity(City newCity);
}

public class MemoryRepository : IRepository
{
    private readonly List<City> cities = new List<City>();

    public IEnumerable<City> Cities => cities;

    public void AddCity(City newCity) => cities.Add(newCity);
}

My Startup class contains the default-generated code from the template. I have made any changes:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
    }
}

Solution

  • For the Dependency Injection framework to resolve IRepository, it must first be registered with the container. For example, in ConfigureServices, add the following:

    services.AddScoped<IRepository, MemoryRepository>();
    

    For .NET 6+, which uses the new hosting model by default, add the following in Program.cs instead:

    builder.Services.AddScoped<IRepository, MemoryRepository>();
    

    AddScoped is just one example of a service lifetime:

    For web applications, a scoped lifetime indicates that services are created once per client request (connection).

    See the docs for more information on Dependency Injection in ASP.NET Core.