Search code examples
c#asp.net-core-webapiasp.net-core-identity

Unable to resolve service for ISystemClock while attempting to activate SecurityStampValidator


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

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

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();

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


Solution

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

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

    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.

    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".