c# – AspNetCore无法解析服务
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – AspNetCore无法解析服务,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4763字,纯文字阅读大概需要7分钟。
内容图文
我正在将Microsoft.AspNetCore.Identity添加到项目中,我得到了
InvalidOperationException: Unable to resolve service for type ‘Microsoft.AspNetCore.Identity.SignInManager’1[Web.Security.Entities.IUser’1[System.Int32]]’ while attempting to activate ‘Web.Security.Services.SecurityService’2[Web.Security.Entities.IUser’1[System.Int32],System.Int32]’.
例外是邮递员的复制品,它编码了一些符号.
这是我的Startup.cs:
public class Startup
{
ServiceProvider serviceProvider;
IConfigurationRoot configurationRoot;
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
configurationRoot = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false)
.AddIniFile("3CXPhoneSystem.ini")
.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
serviceProvider = services
.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace))
.AddSingleton<ISecurityService, SecurityService<IUser<int>, int>>()
.AddSingleton<ITaskService, TaskService>()
.AddTransient<IEmailSender, EmailSender>()
.AddSingleton<ITranslation, Translation>()
.BuildServiceProvider();
services.AddDbContext<SecurityDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("dataContext")));
services.AddIdentity<Web.Security.Entities.User<int>, IdentityRole>()
.AddEntityFrameworkStores<SecurityDbContext>()
.AddDefaultTokenProviders();
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:52170");
}));
services.AddMvc();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
}
// 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();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value) && !context.Request.Path.Value.StartsWith("api"))
{
context.Response.Redirect("/");
}
});
app.UseMvc(routes =>
{
routes.MapRoute(name: "DefaultApi", template: "api/{controller}/{action}/{id?}");
routes.MapRoute("RouteToAngular", "{*url}", defaults: new { controller = "Route", action = "Index" });
});
app.UseAuthentication();
app.UseCors("CorsPolicy");
}
在这里,SecurityService是一个将处理注册/登录/其他身份相关请求的类,它看起来像这样
public class SecurityService<TUser, TKey> : ISecurityService where TUser : class, IUser<TKey>
{
SignInManager<TUser> signInManager;
IConfiguration configuration;
private readonly IHttpContextAccessor httpContextAccessor;
UserManager<TUser> userManager;
IEmailSender emailSender;
IUrlHelper urlHelper;
ISession session;
ILogger<SecurityService<TUser, TKey>> logger;
ITranslation translation;
public SecurityService(
SignInManager<TUser> signInManager,
UserManager<TUser> userManager,
IConfiguration configuration,
IHttpContextAccessor httpContextAccessor,
IEmailSender emailSender,
IUrlHelper urlHelper,
ISession session,
ILogger<SecurityService<TUser, TKey>> logger,
ITranslation translation)
{
this.signInManager = signInManager;
this.userManager = userManager;
this.configuration = configuration;
this.httpContextAccessor = httpContextAccessor;
this.urlHelper = urlHelper;
this.session = session;
this.logger = logger;
this.translation = translation;
this.emailSender = emailSender;
}
IUser.cs:
public interface IUser<TKey>
{
TKey Id { get; set; }
string UserName { get; set; }
string Email { get; set; }
bool EmailConfirmed { get; set; }
}
解决方法:
您需要显式使用IdentityBuilder扩展方法AddSignInManager.
services.AddIdentity<Web.Security.Entities.User<int>, IdentityRole>()
.AddEntityFrameworkStores<SecurityDbContext>()
// Replace ApplicationUser with your concrete user class
.AddSignInManager<SignInManager<ApplicationUser>>()
.AddDefaultTokenProviders();
如果您需要在安全服务中访问它,那么您可以注入它:
public class SecurityService<TUser, TKey> ...
{
public SecurityService(SignInManager<ApplicationUser> signInManager)
{
this.signInManager = signInManager;
}
}
内容总结
以上是互联网集市为您收集整理的c# – AspNetCore无法解析服务全部内容,希望文章能够帮你解决c# – AspNetCore无法解析服务所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。