5 [hostapp.Models.AppRole,hostapp.Data.DataContext,System.Int32,hostapp.Models.AppUserRole,Microsft.AspNetCore.Identity.IdentityRoleClaim
1[System.Int32]]'时,无法解析服务类型为'type hostapp.Data.DataContext'。”
看到这个错误后,我创建了一个新的Web API项目,其中使用了“AddPooledDbContextFactory”,但没有使用“Microsoft.AspNetCore.Identity”,一切顺利。因此我的问题是:
“如何正确地使用带有Microsoft.AspNetCore.Identity的services.AddPooledDbContextFactory,以避免上述错误?”
在“ProjectRoot/Startup.cs”文件中进行操作。
using System.Threading.Tasks;
using hostapp.Data;
using hostapp.GraphQL;
using hostapp.Interfaces;
using hostapp.Models;
using hostapp.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace hostapp
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICookieService, CookieService>();
// EARLIER IMPLEMENTATION WHICH WORKS FINE =>
// services.AddDbContext<DataContext>(options =>
// {
// options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
// });
// CURRENT IMPLEMENTATION WHICH CAUSES AN ERROR
services.AddPooledDbContextFactory<DataContext>(options =>
{
options.UseSqlServer(_config.GetConnectionString("DefaultConnection"));
});
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleValidator<RoleValidator<AppRole>>()
.AddEntityFrameworkStores<DataContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "app-cookie";
// options.Cookie.Expiration = TimeSpan.FromMinutes(30);
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
});
services.AddAuthorization(opt =>
{
opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
});
services
.AddGraphQLServer()
.AddAuthorization()
.AddQueryType<Query>();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(options => options
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("https://localhost:4200")
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.Strict,
// HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
// Secure = CookieSecurePolicy.Always
});
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapGraphQL();
});
}
}
}
在项目根目录/Data/DataContext.cs
中。
using hostapp.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace hostapp.Data
{
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>, AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<AppUserClaim> Claims { get; set; }
public DbSet<AppUserClaimOffender> Offenders { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<AppUser>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppUser)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
builder.Entity<AppRole>()
.HasMany(ur => ur.AppUserRoles)
.WithOne(u => u.AppRole)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
}
}
}
在项目根目录/app.csproj
中。
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.0" NoWarn="NU1605"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="5.0.0"/>
<PackageReference Include="HotChocolate.AspNetCore" Version="11.1.0"/>
<PackageReference Include="HotChocolate.AspNetCore.Authorization" Version="11.1.0"/>
<PackageReference Include="HotChocolate.Data.EntityFramework" Version="11.1.0"/>
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0"/>
</ItemGroup>
</Project>
System.InvalidOperationException: '无法从根提供程序解析作用域服务'Microsoft.AspNetCore.Identity.IPersonalDataProtector'。'
我该如何克服这个问题? - RoXaS