我想在Stormpath中注册后将新用户添加到我的本地数据库。在文档https://docs.stormpath.com/dotnet/aspnetcore/latest/registration.html#registration中有关于注册后处理程序的部分。我有问题因为我无法在StartUp文件中使用UserRepository。 我有错误:
无法解析类型的服务 尝试时'AppProject.Repositories.IUserRepository' 激活'AppProject.Startup'
public void ConfigureServices(IServiceCollection services, IUserRepository userRepository)
{
services.AddStormpath(new StormpathOptions()
{
Configuration = new StormpathConfiguration()
{
Client = new ClientConfiguration()
{
ApiKey = new ClientApiKeyConfiguration()
{
Id = "xxxxxxxxxxx",
Secret = "xxxxxxxxx"
}
}
},
PostRegistrationHandler = (context, ct) =>
{
return MyPostRegistrationHandler(context, ct, userRepository);
}
});
}
private Task MyPostRegistrationHandler(PostRegistrationContext context, CancellationToken ct, IUserRepository userRepository)
{
userRepository.Add(new User(context.Account.Email, context.Account.FullName, context.Account.GivenName, context.Account.Surname, context.Account.Username));
userRepository.SaveChangesAsync();
return Task.FromResult(0);
}
答案 0 :(得分:0)
在这种情况下,我认为它不能解决StartUp中IUserRepository的依赖性。你可以尝试这样的事情。
1)添加扩展方法。
public static IServiceProvider AddServices(this IServiceCollection services)
{
services.AddTransient<IUserRepository, UserRepository>();
// rest of the things.
return services.BuildServiceProvider();
}
2)获取类似这样的userRepository实例。
IServiceCollection services = new ServiceCollection();
services.AddServices();
var provider = services.BuildServiceProvider();
var userRepository = provider.GetRequiredService<IUserRepository>();
ConfigurationServices将没有IUserRepository输入参数。