Asp.Net Core MVC, InvalidOperationException When Navigating to a Controller

Babak Sekandari
Babak Sekandari used Ask the Experts™
on
I've created an Asp.Net core MVC application, database first. .NETCore.App (2.1).
It is the first MVC Core app that I've created.
When I run the application with IIS Express, it loads in the browser correctly.
https://localhost:44312/
Then I create a controller called ApplicantsController.
When I try to navigate to,
https://localhost:44312/Applicants
I get the following error:
InvalidOperationException: Unable to resolve service for type 'SalaryCalculator.Models.Salary_CalculatorContext' while attempting to activate 'SalaryCalculator.Controllers.ApplicantsController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Here is the Startup.cs class:

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

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Babak SekandariProgrammer / Analyst

Author

Commented:
I added the following and now it works:

            var connection = @"Server=ServerName; Database=DataBaseName; Trusted_Connection=true;";
            services.AddDbContext<Models.DataBaseNameContext>(options => options.UseSqlServer(connection));

Could someone please explain why this solution worked?
I mean, what's going on under the hood?
How come it didn't work before and this fixed it?
Programmer / Analyst
Commented:
As noted above:
I added the following and now it works:

            var connection = @"Server=ServerName; Database=DataBaseName; Trusted_Connection=true;";
            services.AddDbContext<Models.DataBaseNameContext>(options => options.UseSqlServer(connection));

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial