尝试激活SecurityStampValidator时无法解析ISystemClock的服务 [英] Unable to resolve service for ISystemClock while attempting to activate SecurityStampValidator

查看:74
本文介绍了尝试激活SecurityStampValidator时无法解析ISystemClock的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将身份添加到我的Web API,但是出现此错误

I try to add Identity to my web API, but get this error

InvalidOperationException:无法解析类型>'Microsoft.AspNetCore.Authentication.ISystemClock'的服务尝试激活>'Microsoft.AspNetCore.Identity.SecurityStampValidator`1 [WebAPI.Models.User>]'.

InvalidOperationException: Unable to resolve service for type >'Microsoft.AspNetCore.Authentication.ISystemClock' while attempting to activate >'Microsoft.AspNetCore.Identity.SecurityStampValidator`1[WebAPI.Models.User>]'.

在Startup.cs中添加身份后,我在其中

after adding Identity in Startup.cs, where I have this

services.AddIdentityCore<User>(options => { });
            new IdentityBuilder(typeof(User), typeof(IdentityRole), services)
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddSignInManager<SignInManager<User>>()
                .AddEntityFrameworkStores<DataContext>();

app.UseAuthentication();

usermodel类为空.一切都加载到数据库中.什么东西少了?感谢您的时间和帮助.

The usermodel class is empty. Everything is loaded into the database. What is missing? I appreciate your time and help.

推荐答案

ISystemClock 通常在 AddAuthentication 调用中注册.您可以在源代码中看到它在这里.

The ISystemClock is usually registered in the AddAuthentication call. You can see it in the sources here.

或者,您可以改为调用 AddDefaultIdentity ,后者依次调用 AddAuthentication 本身.此处的来源.

Or, you could instead call AddDefaultIdentity, which in turn calls AddAuthentication itself. Sources here.

建议您使用其中一种机制,而不要使用 AddIdentityCore .但是,如果由于某种原因而需要调用 AddIdentityCore ,则可以自己注册时钟:

It's recommended you use one of those mechanisms rather than AddIdentityCore. However, if you instead need to call AddIdentityCore for some reason, then you can register the clock yourself:

services.TryAddSingleton<ISystemClock, SystemClock>();

尽管如此,您然后还可能会遇到其他事情,以注册上述方法可以解决的问题.另请参见此问题及其答案.

Though, you then may also run into other things to register that the aforementioned methods take care of. See also this question and its answer.

它是什么- ISystemClock 接口用于获取当前时间. SystemClock 实现从计算机获取实时信息(只需调用 DateTimeOffset.UtcNow ).但是,在测试中,这允许假时钟"实现传入现在的不同值,从而验证场景(例如leap日)和其他临时业务逻辑.这种模式通常称为虚拟时钟"或模拟时钟".

As for what it is - the ISystemClock interface is for getting the current time. The SystemClock implementation gets the real time from the computer (by simply calling DateTimeOffset.UtcNow). However, in testing, this allows a "fake clock" implementation to pass in different values of now, validating scenarios such as leap days, and other temporal business logic. Such a pattern is often called "virtual clock" or "mock the clock".

这篇关于尝试激活SecurityStampValidator时无法解析ISystemClock的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆