asp.net-coreasp.net-core-mvcasp.net-mvc-controller

InvalidOperationException: Unable to resolve service for type '*Models.LandingPageContext' while attempting to activate Controller'


I have a database named "LandingPage", and using this command i have mapped the database tables inside my asp.net mvc core:-

 Scaffold-DbContext "Server=(localdb)\ProjectsV13;Database=LandingPage;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Then i added a controller and chose one of the models, but when i try access the controller i got this exception inside the web browser:-

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Stack Query Cookies Headers Routing 
InvalidOperationException: Unable to resolve service for type 'LandingPage.Models.LandingPageContext' while attempting to activate 'LandingPage.Controllers.QuestionsController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Solution

  • The DbContext needs to be registered as a service in Startup.cs so that it can be injected into the controller in its constructor:

    Startup.cs:

    services.AddDbContext<LandingPageContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    

    QuestionsController.cs:

    public class QuestionsController: Controller
    {
        public QuestionsController(LandingPageContext dbContext)
        {
        }
    }
    

    More information in Dependency injection in ASP.NET Core.