将自定义 UserManager 注入 Controller Net Core 2.1
Inject Custom UserManager To Controller Net Core 2.1
我在尝试将我的 UserManager 注入我的控制器时遇到问题。
这是我的自定义用户管理器:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher,
IEnumerable<IUserValidator<ApplicationUser>> userValidators,
IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors,
IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{
}
public async Task<ApplicationUser> FindAsync(string id, string password)
{
ApplicationUser user = await FindByIdAsync(id);
if (user == null)
{
return null;
}
return await CheckPasswordAsync(user, password) ? user : null;
}
}
这是我的Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.ConfigureCors();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
// Add framework services.
services.AddMvc();
services.AddScoped<ApplicationUserManager>();
var builder = new ContainerBuilder();
builder.Populate(services);
// Registering MongoContext.
builder.RegisterType<MongoContext>().AsImplementedInterfaces<MongoContext, ConcreteReflectionActivatorData>().SingleInstance();
//builder.RegisterType<MongoContext>().As<IMongoContext>();
//Registering ApplicationUserManager.
builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().SingleInstance();
//builder.RegisterType<ApplicationUserManager>().As<ApplicationUserManager>().SingleInstance();
重要的两行是:
builder.RegisterType ApplicationUserManager ().As UserManager ApplicationUser ().SingleInstance();
builder.RegisterType ApplicationUserManager ().As ApplicationUserManager ().SingleInstance;
我的控制器:(我用这两个构造函数测试了它,得到了同样的错误)
public AccountController(ApplicationUserManager applicationUserManager)
{
this.applicationUserManager = applicationUserManager;
}
public AccountController(UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
}
最后是错误:
Autofac.Core.DependencyResolutionException: None of the constructors
found with
'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type
'VotNetMon.ApplicationUserManager' can be invoked with the available
services and parameters: Cannot resolve parameter
'Microsoft.AspNetCore.Identity.IUserStore1[VotNetMon.Entities.ApplicationUser]
store' of constructor 'Void
.ctor(Microsoft.AspNetCore.Identity.IUserStore
1[VotNetMon.Entities.ApplicationUser],
Microsoft.Extensions.Options.IOptions1[Microsoft.AspNetCore.Identity.IdentityOptions],
Microsoft.AspNetCore.Identity.IPasswordHasher
1[VotNetMon.Entities.ApplicationUser],
System.Collections.Generic.IEnumerable1[Microsoft.AspNetCore.Identity.IUserValidator
1[VotNetMon.Entities.ApplicationUser]],
System.Collections.Generic.IEnumerable1[Microsoft.AspNetCore.Identity.IPasswordValidator
1[VotNetMon.Entities.ApplicationUser]],
Microsoft.AspNetCore.Identity.ILookupNormalizer,
Microsoft.AspNetCore.Identity.IdentityErrorDescriber,
System.IServiceProvider,
Microsoft.Extensions.Logging.ILogger1[Microsoft.AspNetCore.Identity.UserManager
1[VotNetMon.Entities.ApplicationUser]])'.
at
Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext
context, IEnumerable1 parameters) at
Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext
context, IEnumerable
1 parameters) at
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1
parameters)
提前致谢
正如错误所说,您必须注册 IUserStore
和通常由 AspNetIdentity 的扩展方法注册的其他依赖项。
services.AddIdentity<ApplicationUser, IdentityRole>();
请注意,这还会添加 cookie 身份验证,因为这是 asp.net identity does. If you persist on doing it with autofac, what is totally legit, you should look here 必须注册的 类。
如果您想一起使用 identity 和 jwt,here 是一个很好的教程,可以指导您完成它。
不直接相关:
- 请始终使用接口,不要注入实现,因此不要配置容器来解析实现。
- 有一种新方法可以结合使用 autofac 和微软的 ioc,这是首选。你可以找到一个例子 here。这是 asp.net core >= 2.0.
想要的方式
我在尝试将我的 UserManager 注入我的控制器时遇到问题。
这是我的自定义用户管理器:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher,
IEnumerable<IUserValidator<ApplicationUser>> userValidators,
IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors,
IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{
}
public async Task<ApplicationUser> FindAsync(string id, string password)
{
ApplicationUser user = await FindByIdAsync(id);
if (user == null)
{
return null;
}
return await CheckPasswordAsync(user, password) ? user : null;
}
}
这是我的Startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.ConfigureCors();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
// Add framework services.
services.AddMvc();
services.AddScoped<ApplicationUserManager>();
var builder = new ContainerBuilder();
builder.Populate(services);
// Registering MongoContext.
builder.RegisterType<MongoContext>().AsImplementedInterfaces<MongoContext, ConcreteReflectionActivatorData>().SingleInstance();
//builder.RegisterType<MongoContext>().As<IMongoContext>();
//Registering ApplicationUserManager.
builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().SingleInstance();
//builder.RegisterType<ApplicationUserManager>().As<ApplicationUserManager>().SingleInstance();
重要的两行是:
builder.RegisterType ApplicationUserManager ().As UserManager ApplicationUser ().SingleInstance();
builder.RegisterType ApplicationUserManager ().As ApplicationUserManager ().SingleInstance;
我的控制器:(我用这两个构造函数测试了它,得到了同样的错误)
public AccountController(ApplicationUserManager applicationUserManager)
{
this.applicationUserManager = applicationUserManager;
}
public AccountController(UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
}
最后是错误:
Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'VotNetMon.ApplicationUserManager' can be invoked with the available services and parameters: Cannot resolve parameter 'Microsoft.AspNetCore.Identity.IUserStore
1[VotNetMon.Entities.ApplicationUser] store' of constructor 'Void .ctor(Microsoft.AspNetCore.Identity.IUserStore
1[VotNetMon.Entities.ApplicationUser], Microsoft.Extensions.Options.IOptions1[Microsoft.AspNetCore.Identity.IdentityOptions], Microsoft.AspNetCore.Identity.IPasswordHasher
1[VotNetMon.Entities.ApplicationUser], System.Collections.Generic.IEnumerable1[Microsoft.AspNetCore.Identity.IUserValidator
1[VotNetMon.Entities.ApplicationUser]], System.Collections.Generic.IEnumerable1[Microsoft.AspNetCore.Identity.IPasswordValidator
1[VotNetMon.Entities.ApplicationUser]], Microsoft.AspNetCore.Identity.ILookupNormalizer, Microsoft.AspNetCore.Identity.IdentityErrorDescriber, System.IServiceProvider, Microsoft.Extensions.Logging.ILogger1[Microsoft.AspNetCore.Identity.UserManager
1[VotNetMon.Entities.ApplicationUser]])'. at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable
1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
提前致谢
正如错误所说,您必须注册 IUserStore
和通常由 AspNetIdentity 的扩展方法注册的其他依赖项。
services.AddIdentity<ApplicationUser, IdentityRole>();
请注意,这还会添加 cookie 身份验证,因为这是 asp.net identity does. If you persist on doing it with autofac, what is totally legit, you should look here 必须注册的 类。
如果您想一起使用 identity 和 jwt,here 是一个很好的教程,可以指导您完成它。
不直接相关:
- 请始终使用接口,不要注入实现,因此不要配置容器来解析实现。
- 有一种新方法可以结合使用 autofac 和微软的 ioc,这是首选。你可以找到一个例子 here。这是 asp.net core >= 2.0. 想要的方式