InvalidOperationException Unable to resolve service for type Interface while attempting to activate Controller

April 17, 2019 0 comments
A dependency is any object that another object requires, Dependency Injection i.e. DI is used for objects which has complex dependencies. While working on one project in asp.net core 2.2 (MVC project, I came across this error)

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'myproject.Areas.myArea.Interfaces.IHolidayRepository' while attempting to activate 'myproject.Areas.myArea.Controllers.AdminController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Dependency Injection (DI) is already part of Core framework, We just have to register our dependencies in startup.cs file under ConfigurationService method.

services.AddTransient<IFoo, Foo>();
services.AddSingleton<IBar, Bar>();
services.AddScoped<IHello, Hello>();

ASP.NET services can be configured with the following:

Transient

Always Different - Transient objects are always different; a new instance is provided to every controller and every service.

Scoped

Same within a request - Scoped objects are the same within a request, but different across different requests

Singleton
Singleton objects are the same for every object and every request (regardless of whether an instance is provided in ConfigureServices)

After Registering Dependency Injection in startup.cs file, we will not get InvalidOperationException Unable to resolve service for type Interface while attempting to activate Controller error.

Reference Article - https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection?view=aspnetcore-2.2