关于asp.net:尝试激活时无法解析” MyApp.ApplicationDbContext”类型的服务

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

在将现有的ASP.Net Core 2.0应用程序集成到基于ASP.Net Core 2.0的新创建的身份验证项目项之后,我也遇到问题。

经过一些调整然后成功构建之后,在浏览器中出现了下一个错误:

An unhandled exception occurred while processing the request.

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

身份验证必须使用尚未搭建的单独数据库

我的Startup.cs如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
}

我的构造函数如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

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

    }
}

我已经更新了构造函数,以明确期望容器知道如何解析的类型:

1
2
3
4
public ApplicationDbContext(DbContextOptions options)
    : base(options)
    {
    }

没有成功,有什么想法吗?


您需要在ConfigureServices()方法中包括以下内容:

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

当前,您仅添加了" SchoolContext" DbContext