Unable to resolve service for type 'MyApp.ApplicationDbContext' while attempting to activate

asp.net asp.net-core asp.net-core-2.0 authentication entity-framework-core

Question

I am having issue after integrated in an existing ASP.Net core 2.0 application a newly created authentication project items based on ASP.Net Core 2.0 too.

after some adjustments then successful build, in the browsser I got the next error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'SpaServices.ApplicationDbContext' while attempting to activate

The authentication has to use a separate database which is not yet scaffolded

My Startup.cs is as follows:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<SchoolContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc()
        .AddRazorPagesOptions(options =>
         {
             options.Conventions.AuthorizeFolder("/Account/Manage");
             options.Conventions.AuthorizePage("/Account/Logout");
         });

    // Register no-op EmailSender used by account confirmation and password reset during development
    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
    services.AddSingleton<IEmailSender, EmailSender>();

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    #region webpack-middleware-registration
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseWebpackDevMiddleware();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    // Call UseWebpackDevMiddleware before UseStaticFiles
    app.UseStaticFiles();
    #endregion

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

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });
    #endregion
}

And my constructor is as below:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

    }
}

I have updated the constructor to explicitly expect a type the container knows how to resolve:

public ApplicationDbContext(DbContextOptions options)
    : base(options)
    {
    }

Without success, any thoughts ?

1
0
2/1/2018 4:20:09 PM

Accepted Answer

You need to include the following in your ConfigureServices() method:

 services.AddDbContext<ApplicationDbContext>(options =>
  options.UseSqlServer(Configuration.GetConnectionString("[Your Connection String Identifier]")));

Currently, you have only added a "SchoolContext" DbContext

3
10/11/2017 2:15:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow